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.

Jasper van den Bosch
  • 3,169
  • 4
  • 32
  • 55
haiprasan86
  • 43
  • 1
  • 1
  • 6
  • please do some research before posting http://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python –  May 30 '12 at 11:52
  • If you need to give a password, I don't think you can do that via subprocess. – mgilson May 30 '12 at 11:52
  • Have you considered using [a proper Python SSH module](http://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python)? – Katriel May 30 '12 at 11:54

3 Answers3

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
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.

mata
  • 67,110
  • 10
  • 163
  • 162
0

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

Jasper van den Bosch
  • 3,169
  • 4
  • 32
  • 55