multiprocess_example.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. '''
  2. Requires paramiko >=1.8.0 (paramiko had an issue with multiprocessing prior
  3. to this)
  4. Example code showing how to use netmiko for multiprocessing. Create a
  5. separate process for each ssh connection. Each subprocess executes a
  6. 'show version' command on the remote device. Use a multiprocessing.queue to
  7. pass data from subprocess to parent process.
  8. Only supports Python2
  9. '''
  10. # Catch Paramiko warnings about libgmp and RandomPool
  11. import warnings
  12. with warnings.catch_warnings(record=True) as w:
  13. import paramiko
  14. import multiprocessing
  15. import time
  16. from datetime import datetime
  17. import netmiko
  18. from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
  19. # DEVICE_CREDS contains the devices to connect to
  20. from DEVICE_CREDS import all_devices
  21. def print_output(results):
  22. print "\nSuccessful devices:"
  23. for a_dict in results:
  24. for identifier,v in a_dict.iteritems():
  25. (success, out_string) = v
  26. if success:
  27. print '\n\n'
  28. print '#' * 80
  29. print 'Device = {0}\n'.format(identifier)
  30. print out_string
  31. print '#' * 80
  32. print "\n\nFailed devices:\n"
  33. for a_dict in results:
  34. for identifier,v in a_dict.iteritems():
  35. (success, out_string) = v
  36. if not success:
  37. print 'Device failed = {0}'.format(identifier)
  38. print "\nEnd time: " + str(datetime.now())
  39. print
  40. def worker_show_version(a_device, mp_queue):
  41. '''
  42. Return a dictionary where the key is the device identifier
  43. Value is (success|fail(boolean), return_string)
  44. '''
  45. try:
  46. a_device['port']
  47. except KeyError:
  48. a_device['port'] = 22
  49. identifier = '{ip}:{port}'.format(**a_device)
  50. return_data = {}
  51. show_ver_command = 'show version'
  52. SSHClass = netmiko.ssh_dispatcher(a_device['device_type'])
  53. try:
  54. net_connect = SSHClass(**a_device)
  55. show_version = net_connect.send_command(show_ver_command)
  56. except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
  57. return_data[identifier] = (False, e)
  58. # Add data to the queue (for parent process)
  59. mp_queue.put(return_data)
  60. return None
  61. return_data[identifier] = (True, show_version)
  62. mp_queue.put(return_data)
  63. def main():
  64. mp_queue = multiprocessing.Queue()
  65. processes = []
  66. print "\nStart time: " + str(datetime.now())
  67. for a_device in all_devices:
  68. p = multiprocessing.Process(target=worker_show_version, args=(a_device, mp_queue))
  69. processes.append(p)
  70. # start the work process
  71. p.start()
  72. # retrieve all the data from the queue
  73. results = []
  74. while any(p.is_alive() for p in processes):
  75. time.sleep(0.1)
  76. while not mp_queue.empty():
  77. results.append(mp_queue.get())
  78. # wait until the child processes have completed
  79. for p in processes:
  80. p.join()
  81. print_output(results)
  82. if __name__ == '__main__':
  83. main()