Remote command execution

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.



import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('raspberry.lan', username='irfan', password='my_strong_password')

stdin, stdout, stderr = client.exec_command('ls -l')

for line in stdout:
    print line.strip('\n')

client.close()