Advertisement
Guest User

Untitled

a guest
Jan 15th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.55 KB | None | 0 0
  1.  
  2. #!/usr/bin/env python
  3. """
  4. merge a config change and commit it.
  5. Requires config.cfg with your config snippet inside at root directory.
  6. """
  7. from napalm import get_network_driver
  8. from jnpr.junos.exception import ConnectAuthError
  9. from iptools import ipv4
  10. import os
  11. import getpass
  12. import argparse
  13.  
  14. class ConnectionFailure(Exception):
  15. pass
  16.  
  17. def make_changes(device, config_file):
  18. """
  19. If all has gone well up to here, you may want to merge the config or
  20. discard it.
  21. """
  22. # merge the local config snip
  23. device.load_merge_candidate(filename=config_file)
  24. # compare the config. If there is no diff, exit and move to next switch or
  25. # exit.
  26. if (device.compare_config()):
  27. commit_answer = "n"
  28. print(device.compare_config())
  29. commit_answer = raw_input("Do you want to commit the changes? (y/N)")
  30. if commit_answer is "y":
  31. commit_result = device.commit_config()
  32. print(commit_result)
  33. else:
  34. print("Rolling back to active configuration... ")
  35. device.discard_config()
  36. else:
  37. print("There is no difference.")
  38.  
  39.  
  40. def open_device(device_ip, driver, creds_dict):
  41. """
  42. Helper function to try all creds on each device. Returns an open device or
  43. None if all creds fail.
  44. """
  45. for _user, _password in creds_dict.iteritems():
  46. _device = driver(device_ip, _user, _password)
  47. _count = 0
  48. try:
  49. _device.open()
  50. return _device
  51. except ConnectAuthError:
  52. # retry with available credentials until list is exhausted
  53. # if no credentials work, log an error.
  54. _count += 1
  55. print("Failed {0} out of {0} login attempts...".format(_count,
  56. len(creds_dict)))
  57. continue
  58. raise ConnectionFailure
  59.  
  60.  
  61. def change(default="config.cfg", username="user", password="password",
  62. switch="switch.cfg"):
  63. """Open the device, merge the config and commit it."""
  64. driver = get_network_driver('junos')
  65.  
  66. # User could have passed an IP address or a path to a file in "switch"
  67. if ipv4.validate_ip(switch):
  68. # It's a single IP address, act on it and quit.
  69. creds_dict = {username: password}
  70. device = open_device(switch, driver, creds_dict)
  71.  
  72. if device:
  73. make_changes(device, default)
  74. device.close()
  75. print("{0} is closed".format(device.hostname))
  76. else:
  77. print("Sionara!")
  78. elif os.path.exists(switch):
  79. # Open the file and read each line into a dict. Each line should be
  80. # formatted as "username password"
  81. switch_file = open(switch, 'r')
  82. for line in switch_file:
  83. print(line)
  84. else:
  85. print("It's not either of those things.")
  86.  
  87.  
  88. if __name__ == "__main__":
  89. parser = argparse.ArgumentParser(description="Process arguments")
  90. parser.add_argument('config', type=str, help='path to file with config'
  91. ' snippet.')
  92. parser.add_argument('user', type=str, help='Username with access to the'
  93. ' switch(es).')
  94. parser.add_argument('switch', type=str, help='Either a single IP address'
  95. ' in X.X.X.X format, or a path to a file containing a'
  96. ' list of switch IP addresses 1 per line.')
  97.  
  98. args = parser.parse_args()
  99. password = getpass.getpass()
  100. for config, switch in a_bunch_of_them:
  101. try:
  102. change(args.config, args.user, password, args.switch)
  103. except ConnectionFailure:
  104. print('failed to connect to {}'.format(switch))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement