SSH with Paramiko

Paramiko is a SSH module for Python, meaning it gives the developers the ability and same time the flexibility to write applications or scripts to connect to a device securely via SSH, and execute commands similar as if you were using your command line interface.

Following we will come up with a very basic script to connect via SSH to a Linux device and run and execute a Linux command remotely.

Same method can be used for other systems such as, network devices, smartphones, etc. This is my setup as below:

Paramiko-BlogLogically first step would be to install Paramiko on your machine (assuming you already have Python installed):

pip install paramiko

Once we make sure that Python combined with Paramiko are running properly, let’s see how we can connect to a remote device via SSH. Get yourself a good text editor or use the command line.

Second step, we need to import the module Paramiko:

import paramiko

And below is the rest of the basic script, so what happens is, we call the paramiko module together with the SSH client method, and assign it under the ‘ssh’ variable. We will use this variable (object instance) for all the rest of the script. Next, the ‘set_missing_host_key’ provides the method to authenticate the keys between host and remote device. The ‘ssh.connect‘ method takes as input the IP address of remote device, the username and the password. The ‘ssh.exec_command’ method takes as input the commands we want to execute on the remote host which happens to be Linux in our case.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(‘192.168.105.207′, username=’testuser’, password=’test123′)

(iin,out,err)=(ssh.exec_command(‘uname -a’))
print out.read()
(iin,out,err)=(ssh.exec_command(‘hostname’))
print out.read()
(iin,out,err)=(ssh.exec_command(‘ifconfig eth0’))
print out.read()

I hope this helps to get up and running with paramiko on python, in case you have a better idea let me know. I know the code could have been written in a better way but I’m not a Python expert 🙂 .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s