7 months, 1 week

Multithreading with Netmiko





Multithreading enables CPUs to run different parts(threads) of a process concurrently. The threading module comes with the standard Python library. 

Automation of networking is always comes with scale requirement, manage or connect or capture data from so many devices, create reports of each device in separate files etc. 

from netmiko import ConnectHandler
from datetime import datetime
from threading import Thread

startTime = datetime.now()
threads = []                            
def checkparallel(ip):            
   device = ConnectHandler(device_type='cisco_ios', ip=ip,username='test', password='test')
   output = device.send_command("show run | in hostname")
   output=output.split(" ")
   hostname=output[1]
   print ("\nHostname for IP %s is %s" % (ip,hostname))
for n in range(1, 5):
   ip="192.168.20.{0}".format(n)
   t = Thread(target=checkparallel, args= (ip,))
   t.start()                              
   threads.append(t)                        

for t in threads:                          
   t.join()                                    
   print ("\nTotal execution time:")
   print(datetime.now() - startTime)

Creating loopback interface                                                                                             

from netmiko import ConnectHandler
from threading import Thread
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()
threads = []                                            
def checkloopback45(ip,interface):
  loopbackpresent=False
  cmdGen = cmdgen.CommandGenerator()
  errorIndication, errorStatus, errorIndex, varBindTable =cmdGen.bulkCmd( cmdgen.CommunityData('mytest'),
     cmdgen.UdpTransportTarget((ip, 161)), 0,25, '1.3.6.1.2.1.2.2.1.2' )
  for varBindTableRow in varBindTable:
    for name, val in varBindTableRow:
       if (interface in val.prettyPrint()):
         loopbackpresent=True
         break                           
  if loopbackpresent:
    print ("\nFor IP %s interface %s is present" % (ip,interface))
  else:                                           
    print ("\nFor IP %s interface %s is NOT present. Pushing the config" % (ip,interface)) 
    pushconfig(ip,interface)

for n in range(1, 5):                     
  ip="192.168.20.{0}".format(n)
  thread = Thread(target=checkloopback45, args= (ip,"Loopback45",))
  thread.start()
  threads.append(thread)

for t in threads:                                                   
  t.join()                                                             

This configuration will be  pushed to each router from Netmiko.The code to identify the routers on which the configuration is missing, and update accordingly, is as follows:

from netmiko import ConnectHandler
from threading import Thread
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()
threads = []
def pushconfig(ip,interface):
   print ("\nConfiguring router %s now..." % (ip))
   device = ConnectHandler(device_type='cisco_ios', ip=ip,username='test', password='test')
   configcmds=["interface "+interface, "description "+interface+" test interface created"]
   device.send_config_set(configcmds)
   checkloopback45(ip,interface)
def checkloopback45(ip,interface):
   loopbackpresent=False
   cmdGen = cmdgen.CommandGenerator()
   errorIndication, errorStatus, errorIndex, varBindTable =cmdGen.bulkCmd(
    cmdgen.CommunityData('mytest'),
     cmdgen.UdpTransportTarget((ip, 161)),  0,25, '1.3.6.1.2.1.2.2.1.2' )

for varBindTableRow in varBindTable:
  for name, val in varBindTableRow:
    if (interface in val.prettyPrint()):
      loopbackpresent=True
      break                                                 
  if loopbackpresent:
     print ("\nFor IP %s interface %s is present" % (ip,interface))
  else:                                                  
     print ("\nFor IP %s interface %s is NOT present. Pushing the
     config" % (ip,interface))
     pushconfig(ip,interface)
for n in range(1, 5):
  ip="192.168.20.{0}".format(n)
  t = Thread(target=checkloopback45, args= (ip,"Loopback45"))
  t.start()                                                             
  threads.append(t)                                                

for t in threads:                                                     
 t.join()                                                                    


Responses(0)







Related