Guest User

Untitled

a guest
Sep 20th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. """
  4. Loop over a list of devies in a YAML file and print their OS version
  5.  
  6. sudo -H pip3 install napalm
  7.  
  8. inventory.yml:
  9. ---
  10. # required: hostname, os
  11. # optional: username, password, timeout, optional_args
  12. R1:
  13. hostname: 192.168.223.2
  14. os: ios
  15. username: admin
  16. password: admin
  17. optional_args:
  18. secret: enable
  19. transport: telnet # Default is SSH
  20. port: 23
  21. verbose: True
  22. R2:
  23. hostname: 192.168.188.2
  24. os: ios
  25. """
  26.  
  27.  
  28. import argparse
  29. from getpass import getpass
  30. import napalm
  31. import sys
  32. import yaml
  33.  
  34.  
  35. def parse_cli_args():
  36.  
  37. parser = argparse.ArgumentParser(
  38. description='Loop over a list of devices in a YAML file and print the device firmware version',
  39. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  40. )
  41. parser.add_argument(
  42. '-i', '--inventory-file',
  43. help='Input YAML inventory file',
  44. type=str,
  45. default='inventory.yml',
  46. )
  47. parser.add_argument(
  48. '-u', '--username',
  49. help='Default username for device access',
  50. type=str,
  51. default=None,
  52. )
  53.  
  54. return vars(parser.parse_args())
  55.  
  56.  
  57. def main():
  58.  
  59. args = parse_cli_args()
  60. args['password'] = getpass("Default password:")
  61.  
  62.  
  63. try:
  64. inventory_file = open(args['inventory_file'])
  65. except Exception:
  66. print('Couldn\'t open inventory file {}'.format(args['inventory_file']))
  67.  
  68. try:
  69. inventory = yaml.load(inventory_file)
  70. except Exception:
  71. return 1
  72.  
  73. inventory_file.close()
  74.  
  75.  
  76. for dev, opt in inventory.items():
  77.  
  78. if 'username' not in opt:
  79. if not args['username']:
  80. print ('No username specified')
  81. return 1
  82. else:
  83. opt['username'] = args['username']
  84.  
  85. if 'password' not in opt:
  86. opt['password'] = args['password']
  87.  
  88. if 'optional_args' not in opt:
  89. opt['optional_args'] = None
  90.  
  91. driver = napalm.get_network_driver(opt['os'])
  92. opt.pop('os')
  93.  
  94. with driver(**opt) as device:
  95.  
  96. print('{}: {}'.format(opt['hostname'], device.get_facts()['os_version']))
  97.  
  98.  
  99. return 0
  100.  
  101.  
  102. if __name__ == '__main__':
  103. sys.exit(main())
Add Comment
Please, Sign In to add comment