Multiprocessing with Netmiko libraries 2


Netmiko is an easy to use Multi-vendor python library to simplify Paramiko SSH connections to network devices.

Original source code can be accessed from https://github.com/ktbyers/netmiko

The following script requires paramiko and netmiko

Collecting same output from hunderds of devices would take a lot of time, this is why I created this small script as a template, you can change the commands in the job(0 function so you can use it for different purposes. Process count can be adjusted according your network response and the number of devices in the list. IP list is a text file which contain one IP address in each line. Alternatively you can use a list as in commented line under main function.

#Library definitions
from netmiko import ConnectHandler
from getpass import getpass
import multiprocessing
from functools import partial
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException
import sys

#test for a successful ConnectHandler
def test_connection():
 try:
 rtr = {
 'device_type': 'cisco_ios_ssh',
 'ip':'192.168.1.1',
 'username':username,
 'password':password,
 }
 device = ConnectHandler(**rtr)
 print("Authentication successfull, connecting devices...")
 device.disconnect()
 except (NetMikoTimeoutException):
  print("Test device timed out \nTo continue with the device list may lock your AD account...")
  sys.exit()
 except (NetMikoAuthenticationException):
  print("Authetication failed, please check your username/password\nYou may lock your AD password...")
  sys.exit()

#Function which is sending IOS commands
def job(username, password, ipaddr):
 rtr = {
 'device_type': 'cisco_ios_ssh',
 'ip': ipaddr,
 'username': username,
 'password': password,
 }
 try:
  device = ConnectHandler(**rtr)
  output = device.send_command('sh cdp ne | begin Device')
  print(output)
  device.disconnect()
 except (NetMikoTimeoutException):
  print("Device timed out " + ipaddr + "\n")
 except (NetMikoAuthenticationException):
  print("Authetication failed for device " + ipaddr +"\n")

#Multitasking to improve script runtime
def parallel_runs(ipaddr):
  pool = multiprocessing.Pool(processes=10)
  newjob=partial(job, username, password)
  result = pool.map(newjob, ipaddr)

#Main Loop
if __name__ == '__main__':
  username = input('Username: ')
  password = getpass()
  test_connection()
  iplist = open('iplist.txt','r')
  ipaddr = iplist.read().splitlines()
  #iplist =['172.16.12.1','172.16.12.2','172.16.13.3','172.16.34.4','172.16.45.5','172.16.46.6','172.16.57.7']
  #ipaddr = iplist
  parallel_runs(ipaddr)
  iplist.close()

Leave a comment

Your email address will not be published.