Perform commands over ssh with Python


Question

I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus:

cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)

However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I automate this in Python? I need to log in with a (known) password to the remote machine, so I can't just use cmd = ssh user@remotehost, I'm wondering if there's a module I should be using?

1
111
8/27/2010 4:09:01 PM

Accepted Answer

I will refer you to paramiko

see this question

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)
166
5/23/2017 12:26:24 PM

Or you can just use commands.getstatusoutput:

   commands.getstatusoutput("ssh machine 1 'your script'")

I used it extensively and it works great.

In Python 2.6+, use subprocess.check_output.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon