Using python and SSH

Previously I have written a post about running telnet with Python. As everyone knows telnet is not the most secure protocol to manage devices. So I want to help you guys out with connecting to devices with SSH using python.

In this example I will be using fabric. Fabric is a python libary that helps you send SSH commands to devices. You can read more on their website about the libary: http://www.fabfile.org/

pip3 install fabric

Since I’m running python3 on my computer I run pip3, if you have installed python2.X you just need to have pip as the first word and not pip3 in the command.

from fabric import Connection
c = Connection(host = '10.78.23.12', user = 'username', connect_kwargs = {'password':'password'})
result = c.run('show version')
print(result)

The first line imports the module needed for connecting using SSH from the fabric libary.
Then the connection to the host is performed with ip, username and password. The last two lines is a variable where the command is added to and a print command to display the information in the variable. The command in this script is just a simple show version to display the information on a cisco switch.

Advertisement