Friday, September 6, 2019

Netmiko Threading assistance requested

I am getting started with Python in general and trying to use netmiko. My first project with it is grabbing configurations automatically from our various switches and saving them to files for upload into a git repo for version control.

So far I have that all working but am looking to speed script as it takes 5mins for about 20 switches and I will be adding many more. My first thought was to try and use threading based off of this gist https://gist.github.com/ktbyers/8005564c5d3711a0e5476dbfd18d8acf

unfortunately, while my script still works and runs, it still seems to be running in series and I am a bit lost as to why currently. Any thoughts would be very much appreciated.

import os import threading import logging from netmiko import Netmiko from netmiko import ConnectHandler from queue import Queue from devices import * logging.basicConfig(filename='/SwitchConfigs/config.log', level=logging.DEBUG) logger = logging.getLogger("netmiko") configpath = '/SwitchConfigs' def ssh_session (key,value): if value['model'] == 'hp1920': #print("running on {}".format(value['name'])) net_conn = Netmiko(**value['device']) net_conn.send_command("_cmdline-mode on\nY\nJinhua1920unauthorized\nscreen-length disable") output = net_conn.send_command("display current-configuration") net_conn.disconnect() filename = os.path.join(configpath,"{}.config".format(value['name'])) f = open(filename,"w") f.write(output) f.close() if value['model'] == 'hp2930': #print("running on {}".format(value['name'])) net_conn = Netmiko(**value['device']) net_conn.send_command("screen-length 1000") output = net_conn.send_command("display current-configuration") net_conn.disconnect() filename = os.path.join(configpath,"{}.config".format(value['name'])) f = open(filename,"w") f.write(output) f.close() if __name__ == "__main__": output_q = Queue() for key,value in switches.items(): my_thread = threading.Thread(target=ssh_session(key, value)) my_thread.start() main_thread = threading.currentThread() for some_thread in threading.enumerate(): if some_thread != main_thread: some_thread.join() while not output_q.empty(): my_dict = output_q.get() for k, val in my_dict.iteritems(): print(k) print(val) 


No comments:

Post a Comment