1

I have a requirement where i need to do the following

I need to ssh to a linux box , run a command , get the output back and i need to do some manipulations.

Is that possible via python subprocess module.

Basically i need a .py code in which i will give the ip address, username and password for connecting to the linux box and run a command and get the output.

Also is that possible via any other modules available in Python.

Suggestions are welcome.

3
  • please do some research before posting stackoverflow.com/questions/1233655/… Commented May 30, 2012 at 11:52
  • If you need to give a password, I don't think you can do that via subprocess. Commented May 30, 2012 at 11:52
  • Have you considered using a proper Python SSH module? Commented May 30, 2012 at 11:54

3 Answers 3

3

Your question is tagged with "paramiko", so why don't you just use that?

I need to ssh to a linux box , run a command , get the output back and i need to do some manipulations.

ssh to a linux box (or any other ssh server):

>>> import paramiko
>>> ssh=paramiko.SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.connect(hostname='localhost', username='haiprasan86', password='secret')
>>> print ssh
<paramiko.SSHClient object at 0xdf2590>

run a command:

>>> _, out, err = ssh.exec_command('ls -l /etc/passwd')
>>> # block until remote command completes
>>> status = out.channel.recv_exit_status()
>>> print status
0

get the output back:

>>> print out.readlines()
['-rw-r--r--. 1 root root 2351 Mar 27 10:57 /etc/passwd\n']

I don't know what manipulations you want to do.

Sign up to request clarification or add additional context in comments.

Comments

0

If it's just one command, you can simply append it to the command line:

ssh user@host "echo foo"

would then return foo. If you use ssh-agent with your public key in the remote host's ~/.ssh/authorized_keys-file then you don't even need to ask for the password.

Comments

0

Other options would be fabric or if you need to interact with the remote command, fexpect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.