Connecting to network devices concurrently using Python
Posted on January 13, 2020
There was one issue with my previous </a>about using python to find interfaces on a certain vlan and this was the length of time it took to actually complete the script. From start to finish the script took 3 minutes and 20 seconds, which is still significantly better than doing it manually but it can be improved.
The reason it took so long was that it was connecting to each device in the list one at a time, doing the tasks and then moving on to the next device. I found a blog post by Kirk Byers (creator of netmiko) which pointed towards his GitHub page and this had examples of using processes to connect to devices concurrently.
The code is below and it has been modified significantly to what is in Kirk’s GitHub page as I used that as a jumping off point. This script now takes about 6 seconds to run through the same amount of devices.
The first thing to know is that I have a file called my_devices.py which acts as an inventory file. It’s basic structure is as below and it can be easily expanded for whatever devices you have.
I am also using cprint to make terminal output look nice, but this can be ignored if you do not want to use cprint.
On my github page you can find a barebones script which can be modified easily.
The parts that need to be explained in a bit more detail is the show_ciscon_commands function.
What this does is connects to the device, sends the show int status command then this output is parsed using ntc templates. ntc templates parses commands into a nice dictionary which can be worked with a lot easier than the normal output. The next part is the for loop, which loops through the sh_commands_parsed output and looks for the values you have specified.
Again there is room for improvement in the script as there always is, but I have been improving all my attempts over the last few months so feeling hopeful about the next project!