Perform commands over ssh with 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.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.

Perform commands over ssh with Python

Keep it simple. No libraries required.

import subprocess

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

Leave a Reply

Your email address will not be published. Required fields are marked *