Perform commands over ssh with Python Perform commands over ssh with Python python python

Perform commands over ssh with Python


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)

If you are using ssh keys, do:

k = paramiko.RSAKey.from_private_key_file(keyfilename)# OR k = paramiko.DSSKey.from_private_key_file(keyfilename)ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=host, username=user, pkey=k)


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.


Keep it simple. No libraries required.

import subprocesssubprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()