SSH automation using Python

Sometimes its required for us to be able to communicate with a remote host using automation. To do it in bash we can use the expect command. But do it in Python, we can use a package named paramiko.

Installing Paramiko

Installation is quite simple. It can be done using the pip or pip3 command

$ pip install paramiko

Note: based on your setup, you might need to use sudo as well before the pip command

Connecting to the Remote server

Connection to the remote server can be done using a username and password

import paramiko

ssh = paramiko.SSHClient()

# Below we set the policy to auto add hosts to known_hosts 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect("myserver.com", 22, "username", "password")

Signature of the connect method is as below

connect(self, hostname, port, username, password, pkey, key_filename, 
timeout, allow_agent, look_for_keys, compress, sock, 
gss_auth, gss_kex, gss_deleg_creds, gss_host, banner_timeout)

So if you connect using the key, then you can provide the same in the key_filename parameter

Executing a command

To execute a command we use the exec_command method, which retruns us 3 channels for input, output and error respectively

stdin, stdout, stderr = ssh.exec_command("date")

print stdout.readlines()

Above command produces the below output

[u'Sat Jun  02 06:55:08 UTC 2017\n']

If there is any error, that can be accessed using the stderr channel

print stderr.readlines()

If you have a complex job then look at Fabric API