Advertisement
Guest User

junos_set_config_change.py

a guest
Sep 14th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.11 KB | None | 0 0
  1. import os
  2. import sys
  3. import getpass
  4. import datetime
  5. import pyping
  6. import colorama
  7.  
  8. from termcolor import colored
  9. from termcolor import cprint
  10. from lxml import etree
  11.  
  12. from jnpr.junos import Device
  13. from jnpr.junos.utils.config import Config
  14. from jnpr.junos.exception import *
  15. from jnpr.junos.facts import *
  16.  
  17. """ This is used to get the name of the IP list that will be used for the script """
  18. location = raw_input("Select location: ")
  19.  
  20. colorama.init()
  21.  
  22. bold_green = lambda x: cprint(x, 'green', attrs=['bold'])
  23. green = lambda x: cprint(x, 'green')
  24. yellow = lambda x: cprint(x, 'yellow', attrs=['bold'])
  25. red = lambda x: cprint(x, 'red', attrs=['bold'], file=sys.stderr)
  26.  
  27. """ The username is specified here and you will be prompted for a password. """
  28. username = raw_input('Username:')
  29. password = getpass.getpass("Password:")
  30.  
  31. """ This is the error log """
  32. fail_log = 'junos-config-change-error-report-%s.txt' % location
  33.  
  34. """ This is the 'out-file' that the script writes results to """
  35. f = open('junos-config-change-results-%s.txt' % location, 'w')
  36.  
  37. fail = open(fail_log, 'a')
  38.  
  39. def update_config(host):
  40.     """Our main function 'update_config' is defined below"""
  41.  
  42.     def date_time():
  43.         """function used to grab the date and time in an easy to read format"""
  44.         date = str(datetime.datetime.now())
  45.         return date
  46.  
  47.     def snmp_location():
  48.         """function used to grab the contents of the snmp description in the config"""
  49.         try:
  50.             data = dev.rpc.get_config() # use 'normalize=True' when possible
  51.             location = data.xpath('//location')
  52.             location = etree.tostring(location[0])
  53.             location = location.replace("<location>", "").replace("</location>\n", "")
  54.             return location
  55.         except Exception as err:
  56.             print "Error in snmp_location()!"
  57.             f.write("Error: snmp_location(): {0} ".format(err) + '\n')
  58.  
  59.     model = dev.facts['model']
  60.  
  61.     f.write("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n")
  62.     f.write("Working on: " + host + '\n')
  63.     f.write(snmp_location() + '\n')
  64.     print "Working on:", host
  65.     print snmp_location()
  66.     f.write(date_time() + '\n')
  67.     print datetime.datetime.now()
  68.     print "Model:", model
  69.     f.write("Model: " + model + '\n')
  70.  
  71.     """ This binds Config to dev """
  72.     conf = Config(dev)
  73.  
  74.     hostname = dev.facts['hostname']
  75.  
  76.     """ This is where the ping function is defined.
  77.         This function is used later in the script to test connectivity to the SRX """
  78.     def pingtest(host):
  79.         """function is used to see if the host is still pingable"""
  80.         tryping = pyping.ping(host.strip())
  81.         if tryping.ret_code is 0:
  82.             return True
  83.         else:
  84.             return False
  85.  
  86.     """ This is where the Juniper 'set' commands are defined.
  87.         This command is just used as an example and is only locally significant """
  88.     set_commands = """
  89.     set system scripts op file sit.slax description "null"
  90.     """
  91.  
  92.     f.write("Locking the configuration...\n")
  93.     print "Locking the configuration..."
  94.  
  95.     """ This command locks the configuration for a 'configure exclusive' """
  96.     try:
  97.         conf.lock()
  98.         f.write("Configuration locked\n")
  99.         green("Configuration locked")
  100.     except (KeyboardInterrupt, SystemExit):
  101.         raise
  102.     except LockError as err:
  103.         f.write("Error: Unable to lock configuration: {0} ".format(err) + '\n')
  104.         red("Error: Unable to lock configuration...")
  105.     except Exception as err:
  106.         print err
  107.         f.write("Error in conf.lock(): {0} ".format(err) + '\n')
  108.  
  109.     f.write("Checking for uncommitted configuration changes...\n")
  110.     print "Checking for uncommitted configuration changes..."
  111.  
  112.     """ This command is the equivilant of 'show | compare' """
  113.     if conf.diff() is None:
  114.         f.write("There are no uncommitted changes\n")
  115.         green("There are no uncommitted changes")
  116.     else:
  117.         f.write("There are uncommitted changes...rolling back...\n")
  118.         yellow("There are uncommmitted changes...rolling back...")
  119.         try:
  120.             conf.rollback(rb_id=0) # This command issues a rollback. 'rb_id=' is the rollabck number: 0 - 5
  121.             f.write("Configuration has been rolled back to 0\n")
  122.             f.write("Locking configuration...\n")
  123.             green("Configuration has been rolled back!")
  124.             try:
  125.                 f.write("Double checking 'show | compare'\n")
  126.                 print "Double checking 'show | compare'"
  127.                 if conf.diff() is None:
  128.                     try:
  129.                         print "Locking configuration..."
  130.                         conf.lock() # This command is used to lock the configuration in the event that the first
  131.                         f.write("Configuration locked\n") # configuiration lock failed due to
  132.                         print "Configuration locked"      # uncommitted configuration changes
  133.                     except (KeyboardInterrupt, SystemExit):
  134.                         raise
  135.                     except LockError as err:
  136.                         f.write("Unable to lock configuration: {0} ".format(err) + '\n')
  137.                         red("Error: Unable to lock configuration!")
  138.                         f.write("Exiting this device immediately!\n")
  139.                         print "Exiting this device immediately!"
  140.                         return
  141.                     except Exception as err:
  142.                         print err
  143.                         f.write("Error in conf.lock(): {0} ".format(err) + '\n')
  144.                         return
  145.  
  146.                 else:
  147.                     fail.write("There were problems removing the pending \
  148.                         configuration changes on " + hostname + '\n')
  149.                     f.write("There were problems removing the pending configuration changes\n")
  150.                     f.write("Exiting now...\n")
  151.                     print "There were problems removing the pending configuration changes"
  152.                     print "Exiting now"
  153.                     return
  154.             except (KeyboardInterrupt, SystemExit):
  155.                 raise
  156.             except Exception as err:
  157.                 fail.write("There were probelms running 'show | compare' on " + hostname + '\n')
  158.                 fail.write(err + '\n')
  159.                 f.write("There were errors running 'show | compare'\n")
  160.                 f.write("Exiting device immediately\n")
  161.                 print "There were errors running 'show | compare' "
  162.                 print err
  163.                 print "Exiting now"
  164.                 return
  165.  
  166.         except (KeyboardInterrupt, SystemExit):
  167.             raise
  168.         except Exception as err:
  169.             fail.write("Failed to rollback on " + hostname + '\n')
  170.             fail.write(err + '\n')
  171.             f.write("Failed to rollback...\n")
  172.             f.write("Exiting this device\n")
  173.             print "Failed to rollback..."
  174.             print err
  175.             print "Exiting this device"
  176.             dev.close()
  177.             return
  178.  
  179.     f.write("Loading the configuration changes...\n")
  180.     print "Loading the configuration changes..."
  181.  
  182.     """ This command loads the configuration changes.
  183.         The 'merge=False' parameter means it will overwrite existing configurations """
  184.     try:
  185.         conf.load(set_commands, format='set', merge=False)
  186.     except (KeyboardInterrupt, SystemExit):
  187.         raise
  188.     except ValueError as err:
  189.         fail.write("Failed to load configuration changes {0} ".format(err) + '\n')
  190.         f.write("Loading the configuration changes failed: {0} ".format(err) + '\n')
  191.         f.write("Exiting the device\n")
  192.         red(err.message)
  193.         return
  194.     except ConfigLoadError as err:
  195.         fail.write("Failed to load configuration changes {0} ".format(err) + '\n')
  196.         f.write("Loading the configuration changes failed: {0} ".format(err) + '\n')
  197.         f.write("Exiting the device\n")
  198.         red(err.message)
  199.         return
  200.     except Exception as err:
  201.         print err
  202.         f.write("Error: Failed to load configuration changes {0} ".format(err) + '\n')
  203.         return
  204.  
  205.     try:
  206.         f.write("Checking commit...\n")
  207.         print "Checking commit..."
  208.         conf.commit_check()
  209.         f.write("Commit check passed\n")
  210.         print "Commit check passed with 0 errors"
  211.     except CommitError as err:
  212.         fail.write("Commit check did NOT pass {0} ".format(err) + '\n')
  213.         f.write("Commit check did NOT pass! {0} ".format(err) + '\n')
  214.         print "Commit check did NOT pass! Check log file for more"
  215.         return
  216.     except RpcError as err:
  217.         fail.write("Commit check did NOT pass {0} ".format(err) + '\n')
  218.         f.write("Commit check did NOT pass! {0} ".format(err) + '\n')
  219.         print "Commit check did NOT pass! Check log file for more"
  220.         return
  221.     except Exception as err:
  222.         print err
  223.         f.write("Commit check did NOT pass: {0} ".format(err) + '\n')
  224.         return
  225.  
  226.     f.write("Committing the configuration...\n")
  227.     print "Committing the configuration changes..."
  228.  
  229.     """ This command commits the config with a comment and 1 minute to confirm """
  230.     try:
  231.         conf.commit(confirm=1)
  232.         f.write("Commit confirm 1 successful!\n")
  233.         bold_green("Commit confirm 1 successful!")
  234.         print "Verifying connectivity..."
  235.     except (KeyboardInterrupt, SystemExit):
  236.         raise
  237.     except CommitError as err:
  238.         fail.write("Commit failed or broke connectivity: {0} ".format(err) + '\n')
  239.         f.write("Commit failed or broke conectivity: {0} ".format(err) + '\n')
  240.         f.write("Pinging to verify...\n")
  241.         red("Commit failed or broke connectivity")
  242.         print "Pinging to verify..."
  243.     except RpcTimeoutError as err:
  244.         fail.write("Commit failed or broke connectivity: {0} ".format(err) + '\n')
  245.         f.write("Commit failed or broke conectivity: {0} ".format(err) + '\n')
  246.         f.write("Pinging to verify...\n")
  247.         red("Commit failed or broke connectivity")
  248.         print "Pinging to verify..."
  249.     except Exception as err:
  250.         print err
  251.         f.write("Commit failed or broke connectivity: {0} ".format(err) + '\n')
  252.  
  253.     """ This command is used to ping the host to see if applying the configuration broke the connectivity """
  254.     if pingtest(host) is True:
  255.         f.write(host.strip() + " looks up from here\n")
  256.         f.write("Confirming the configuration...\n")
  257.         print host.strip(), "looks UP from here"
  258.         print "Confirming the configuration..."
  259.         try:
  260.             conf.commit(comment="COMMIT MESSAGE GOES HERE") # If the ping succeeds it issues a 'commit confirm'
  261.             f.write("Configuration was confirmed!\n")
  262.             f.write("Unlocking the configuration...\n")
  263.             bold_green("Configuration was confirmed!")
  264.             print "Unlocking the configuration..."
  265.             try:
  266.                 conf.unlock() # This command unlocks the configuration
  267.             except (KeyboardInterrupt, SystemExit):
  268.                 raise
  269.             except UnlockError as err:
  270.                 f.write("Unlocking the configuration failed: {0} ".format(err) + '\n')
  271.                 red("Unlocking the configuration failed")
  272.             except Exception as err:
  273.                 print err
  274.                 f.write("Error unlocking the configuration: {0} ".format(err) + '\n')
  275.  
  276.             f.write("Closing connection to " + hostname + '\n')
  277.             print "Closing the connection to", hostname
  278.             try:
  279.                 dev.close() # This command closes the device connection
  280.             except (KeyboardInterrupt, SystemExit):
  281.                 raise
  282.             except Exception as err:
  283.                 f.write("Failed to close: " + err + hostname + '\n')
  284.                 print "Failed to close", hostname, err
  285.  
  286.         except (KeyboardInterrupt, SystemExit):
  287.             raise
  288.         except CommitError as err:
  289.             fail.write("Commit failed: {0} ".format(err) + '\n')
  290.             f.write("Failed to commit changes: {0} ".format(err) + '\n')
  291.             print "Failed to commit the changes"
  292.         except RpcTimeoutError as err:
  293.             print "RPC timeout error on %s!" % host
  294.             f.write("RPC timeout error on %s!" % host + '\n')
  295.             fail.write("RPC timeout error on %s!" % host + '\n')
  296.         except Exception as err:
  297.             print err
  298.             f.write("Error: {0} ".format(err) + '\n')
  299.  
  300.            """ This detects ping failure. If the ping fails,
  301.                the script will exit the current host without confirming
  302.                the commit and the configuration will rollback in 1 minute """
  303.     else:
  304.         f.write(host.strip() + " looks DOWN from here...\n")
  305.         fail.write(host + "looks down from here\n")
  306.         f.write("Moving on to the next host...\n")
  307.         print host, "looks down from here..."
  308.         print "Moving on to the next host..."
  309.  
  310.     f.write("Completed: " + hostname + '\n')
  311.     f.write("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n")
  312.     print "Completed:", hostname
  313.     print ""
  314.  
  315. """ This is used to loop through every host entry in the list specified """
  316. with open('C:\\ip_lists/%s-list.txt' % location) as infile:
  317.     for host in infile:
  318.  
  319.         """ This is used to test connectivity to a host before attempting to connect """
  320.         dev = Device(host=host.strip(), user=username, password=password) # change pass function
  321.         try:
  322.             dev.open()
  323.         except (KeyboardInterrupt, SystemExit):
  324.             raise
  325.         except ConnectError as err:
  326.             fail.write("Error: Cannot connect to device: {0} ".format(err) + '\n')
  327.             f.write("Error: Cannot connect to device: {0} ".format(err) + '\n\n')
  328.             yellow("Error: Cannot connect to device: {0} ".format(err))
  329.             continue
  330.         except Exception as err:
  331.             print err
  332.             f.write("Error: Cannot connect to device: {0} ".format(err) + '\n')
  333.             continue
  334.         update_config(host)
  335.  
  336. f.close()
  337. fail.close()
  338.  
  339. if os.path.getsize(fail_log) == 0:
  340.     os.remove(fail_log)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement