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(https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html) 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.load_system_host_keys()
ssh.connect('user@server:path')
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.

raja
Published on 28-Dec-2017 07:08:06
Advertisements