Advertisement
Guest User

Untitled

a guest
Feb 11th, 2020
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import csv
  2. import threading
  3. from queue import Queue
  4. import getpass
  5. from netmiko import ConnectHandler
  6. import logging
  7. from datetime import datetime
  8. logging.basicConfig(filename='test.log', level=logging.DEBUG)
  9. logger = logging.getLogger("netmiko")
  10.  
  11. # Define username and password to login to all routers with
  12. platform = input("Platform?: ")
  13. username = input("Username?: ")
  14. password = getpass.getpass(prompt="Password?: ")
  15. command = input("Command You'd Like To Run?: ")
  16. devicelist = input("File containing list of network devices?: ")
  17. outputtxt = input("Output file name?: ")
  18. port = input("Port?: ")
  19.  
  20. # Define router IPs, you could also make a dictionary imported from a CSV file, or create a list from a text file of hostnames
  21. routers = open(devicelist)
  22.  
  23. def ssh_session(router, output_q):
  24. # Place what you want each thread to do here, for example connect to SSH, run a command, get output
  25. output_dict = {}
  26. hostname = router
  27. router = {'device_type': platform, 'ip': router.strip(), 'username': username, 'password': password, 'secret': password, 'port': port, 'verbose': False, }
  28. ssh_session = ConnectHandler(**router)
  29. output = ssh_session.send_command(command)
  30. output_dict[hostname] = output
  31. output_q.put(output_dict)
  32.  
  33.  
  34. if __name__ == "__main__":
  35.  
  36. output_q = Queue()
  37. outfile = open(outputtxt, 'w')
  38. print(datetime.now())
  39.  
  40. # Start thread for each router in routers list
  41. for router in routers:
  42. my_thread = threading.Thread(target=ssh_session, args=(router, output_q))
  43. my_thread.start()
  44.  
  45. # Wait for all threads to complete
  46. main_thread = threading.currentThread()
  47. for some_thread in threading.enumerate():
  48. if some_thread != main_thread:
  49. some_thread.join()
  50.  
  51. # Retrieve everything off the queue
  52. while not output_q.empty():
  53. my_dict = output_q.get()
  54. for k, val in my_dict.items():
  55. print(k)
  56. print(val)
  57.  
  58. # Write info to file
  59. outfile.write(output)
  60.  
  61. print(datetime.now())
  62. outfile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement