How to perform different commands over ssh with Python?

PythonServer Side ProgrammingProgramming

The simplest way to use SSH using python is to use paramiko. You can install it using −

$ pip install paramiko

To use paramiko, ensure that you have correctly set up SSH keys( on the host machine and when running the python script, these keys are accessible. Once that is done use the following code to connect to a remote server using ssh −

from paramiko import SSHClient
ssh = SSHClient()
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls')
print(ssh_stdout) #print the output of ls command

You can use the exec_command function to run any command supported by the server you're connected to over ssh. Running the above code will give you the directory listing on the remote server.

Updated on 18-Feb-2020 07:15:27