Skip to content

Instantly share code, notes, and snippets.

@ktbyers
Created February 24, 2017 20:10
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ktbyers/8005564c5d3711a0e5476dbfd18d8acf to your computer and use it in GitHub Desktop.
Save ktbyers/8005564c5d3711a0e5476dbfd18d8acf to your computer and use it in GitHub Desktop.
Netmiko Threading from a CSV file
import csv
import threading
from Queue import Queue
from getpass import getpass
from netmiko import ConnectHandler
from datetime import datetime
USER = 'pyclass'
PASSWORD = getpass()
def ssh_session(row, output_q):
output_dict = {}
hostname = row['hostname']
router = {'device_type': 'cisco_ios', 'ip': hostname, 'username': USER, 'password': PASSWORD, 'verbose': False, }
ssh_session = ConnectHandler(**router)
output = ssh_session.send_command("show version")
# Add data to the queue
output_dict[hostname] = output
output_q.put(output_dict)
if __name__ == "__main__":
print datetime.now()
output_q = Queue()
outfile = open('vlan2config.conf', 'w')
with open('routers.csv') as routerFile:
routerDict = csv.DictReader(routerFile)
for row in routerDict:
# Start all threads
print row
my_thread = threading.Thread(target=ssh_session, args=(row, output_q))
my_thread.start()
# Wait for all threads to complete
main_thread = threading.currentThread()
for some_thread in threading.enumerate():
if some_thread != main_thread:
some_thread.join()
# Retrieve everything off the queue
while not output_q.empty():
my_dict = output_q.get()
for k, val in my_dict.iteritems():
print k
print val
# Write info to file
#outfile.write(output)
outfile.close()
print datetime.now()
@OfWolfAndMan
Copy link

@ktbyers, is multithreading a part of netmiko as of today, or is this a one-off solution?

@Chikkis
Copy link

Chikkis commented Aug 26, 2019

import Queue is now small-letter queue

print row # this line is giving error. so converted it into string type and print shows as null.
print k # is same effect.
print val # this too is same.

for row in routerDict: # loop it does not enter into it; as there is a oject shows empty.

.csv file contains as follows

10.20.30.40, 20.30.40.50, 30.40.50.60

what i am missing here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment