tags:

views:

115

answers:

4

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?

+2  A: 

Have you had a look at Fabric? It allows you to do all sorts of remote stuff over SSH using python.

t3k76
+3  A: 

I prefer you paramiko

see the stackoverflow question

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh_session.exec_command(cmd_to_execute)
Tumbleweed
Ah, thanks for that, didn't find that in the search. I'll give it a whirl.
fredley
A: 

Or you can just use

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

I used it extensively and it works great.

powerrox
A: 

I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.

Eric Snow