Advertisement
Guest User

junos_set_config_change.py

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