Network automation: Python and Netmiko
Lately, I’ve been using Python to eliminate some boring chores. I wanted to share a short example on how you could use Netmiko to connect to multiple devices.
Netmiko is a multi-vendor library to simplify Paramiko SSH connections to network devices. It's written in Python and I have found this to be quite a useful library. You can retrieve information or alter the device configuration from different vendors in a very easy way by using the same generic function over and over again. Take the following two functions for example:
These two functions can be used to loop through a list of hosts and fire off some show or configuration commands. By feeding the function with a vendor type, you can easily use these two functions for the vendors supported by Netmiko. Some of these vendors include Juniper, Cisco, Arista and Huawei. I have had some great experiences using Netmiko for both Juniper and Huawei. I have used it to issue show commands as well as configuration commands. Let’s have a look at two examples where the functions are used for some screen scraping.
I put the code that is shown above into a file called ‘connect.py’. I then created two different scripts in the same directory and imported the function by using ‘from connect import *’.
Example configuring two Juniper devices:
Example issuing show commands to all Huawei router inside a certain IP range:
Sure makes things easy!
Altering either example to connect to another vendor requires little more than simply altering the ‘device’ and ‘commands’ variables. Netmiko will take care of the rest.
Netmiko was created by Kirk Byers and you can find the code here.
To find out what Kirk Byers himself has to say about his open-source Python library, check this. As an example, he shows you how to retrieve a 'show arp' from devices consisting of different vendors and platforms.
Ps, Netmiko can be installed by issueing ‘pip install netmiko’. PIP, if it isn’t installed already, can be installed by issuing ‘sudo apt-get -y install python-pip’