Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import threading
- from queue import Queue
- import getpass
- from netmiko import ConnectHandler
- import logging
- from datetime import datetime
- logging.basicConfig(filename='test.log', level=logging.DEBUG)
- logger = logging.getLogger("netmiko")
- # Define username and password to login to all routers with
- platform = input("Platform?: ")
- username = input("Username?: ")
- password = getpass.getpass(prompt="Password?: ")
- command = input("Command You'd Like To Run?: ")
- devicelist = input("File containing list of network devices?: ")
- outputtxt = input("Output file name?: ")
- port = input("Port?: ")
- # Define router IPs, you could also make a dictionary imported from a CSV file, or create a list from a text file of hostnames
- routers = open(devicelist)
- def ssh_session(router, output_q):
- # Place what you want each thread to do here, for example connect to SSH, run a command, get output
- output_dict = {}
- hostname = router
- router = {'device_type': platform, 'ip': router.strip(), 'username': username, 'password': password, 'secret': password, 'port': port, 'verbose': False, }
- ssh_session = ConnectHandler(**router)
- output = ssh_session.send_command(command)
- output_dict[hostname] = output
- output_q.put(output_dict)
- if __name__ == "__main__":
- output_q = Queue()
- outfile = open(outputtxt, 'w')
- print(datetime.now())
- # Start thread for each router in routers list
- for router in routers:
- my_thread = threading.Thread(target=ssh_session, args=(router, 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.items():
- print(k)
- print(val)
- # Write info to file
- outfile.write(output)
- print(datetime.now())
- outfile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement