Fix Python – Perform commands over ssh with Python


Asked By – fredley

I’m writing a script to automate some command line commands in Python. At the moment, I’m doing calls like this:

cmd = "some unix command"
retcode =,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?

Now we will see solution for issue: 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)

This question is answered By – shahjapan

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0