def init_globals_and_options(): """ Initializes all the global variables that are used in this POAP script """ global log_hdl, syslog_prefix global options # A list of valid options log_hdl = None syslog_prefix = "" options["destination_path"] = "poap/sudi_fs/" options["required_space"] = 1000 # --- USB related settings --- # USB slot info. By default its USB slot 1, if not specified specifically. # collina2 has 2 usb ports. To enable poap in usb slot 2 user has to set the # value of usbslot to 2. slot_choice_1 = cli("dir usb1:") slot_choice_2 = cli("dir usb2:") # Check for finding whether slot 1 is empty or is an incorrect USB entered. if 'usb is not present' in slot_choice_1: if 'usb is not present' in slot_choice_2: poap_log( "Either valid USB is not entered, or inserted USB is corrupt. Please check again." ) abort( "Either valid USB is not etered, or inserted USB is corrupt. Please check again." ) else: options["usb_slot"] = 2 options["usb_slot"] = 1
def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: print "Caught an error inside critical section" print "Rolling back to checkpoint %s" % self.name cisco.cli('rollback running-config checkpoint %s' % self.name) else: print "Exited critical section without error"
def check_slot_numbers(): active_slot_number = cli("show module | in active") active_slot_number = active_slot_number.strip(' ')[0] standby_slot_number = cli("show module | in standby") standby_slot_number = standby_slot_number.strip(' ')[0] return (active_slot_number, standby_slot_number)
def wrapper(*args, **kwargs): print 'Calling original function' result = func(*args, **kwargs) print 'Saving running config' cisco.cli('copy r s') return result
def wrapper(*args, **kwargs): print 'Calling original function' result = func(*args, **kwargs) print 'Saving running config with vdc all: %r' % vdc_all if vdc_all: cisco.cli('copy r s vdc-all') else: cisco.cli('copy r s') return result
def check_diag(active_slot_number, standby_slot_number): diag_output_active = cli("show diagnostic result module {} | include \" CompactFlash\"".format(active_slot_number)) diag_result_active = diag_output_active.split(' ')[3].rstrip() diag_output_standby = cli("show diagnostic result module {} | include \" CompactFlash\"".format(standby_slot_number)) diag_result_standby = diag_output_standby.split(' ')[3].rstrip() print('Diag results:\n slot {} = {}\n slot {} = {}'\ .format(active_slot_number, diag_result_active, standby_slot_number, diag_result_standby)) check_raid(active_slot_number, standby_slot_number)
def install_bios(): try: cli ("config terminal ; terminal dont-ask") ret = cli ("config terminal ; install all nxos %s bios" % system_image_dst) poap_log(poap_script_log_handler,"Bios successfully upgraded to version %s" % get_bios_ver()) except Exception as inst: poap_log(poap_script_log_handler, "bios upgrade failed: %s" % inst) poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) cleanup_files() poap_script_log_handler.close() exit(1)
def main(): global serial_number event_log("Running script version "+script_version) serial_number = cli("show version | grep 'Processor Board ID' | cut -d ' ' -f 6").strip() event_log("Device Serial Number: " + serial_number) counter = 0 while cli('show interface mgmt 0 brief | grep mgmt0').split()[3] == '--' and counter < 10: time.sleep(10) counter = counter + 1 update_device_state_in_nso(serial_number, 'ONLINE')
def get_Description_info(iInfo): if(iInfo.find('Eth') == 0 or iInfo.find('Po')==0): intCmd = 'sh int desc | inc ' + iInfo intCmdResult = cisco.cli(intCmd) if(intCmdResult != ''): intCmdResultList = intCmdResult.split('\n') IP_info[Desc] = intCmdResultList[0][25:].strip()
def get_cli(cmd): global g_trace try: op = cisco.cli(cmd) except: if cmd.find("|") != -1: # this might be benign, because command executed after pipe returned non-zero rc sev = info else: sev = error log("exception for: '" + cmd + "'", sev) # in iluka we still get the output... op = sys.exc_value if type(op) == tuple: op = op[1] # for obscure reason cli() on n6k returns tuple (status, output), not string elif type(op) == str: op = op.split("\n") if g_trace: try: trace_file = open(g_trace_file_path, "a+") trace_file.write("cmd:" + cmd + "\n") for line in op: trace_file.write(line + "\n") trace_file.close() except: log("exception while saving trace data, disabling tracing", error) g_trace = False return op
def check_raid(active_slot_number, standby_slot_number): raid_output_active = cli("slot {} show system internal raid | grep \"RAID data from CMOS\"".format(active_slot_number)) for line in raid_output_active.splitlines(): if re.search(r'RAID data from CMOS', line): raid_value_active = line.split(' ')[6] raid_output_standby = cli("slot {} show system internal raid | grep \"RAID data from CMOS\"".format(standby_slot_number)) for line in raid_output_standby.splitlines(): if re.search(r'RAID data from CMOS', line): raid_value_standby = line.split(' ')[6] print('RAID results:\n slot {} = {}\n slot {} = {}'\ .format(active_slot_number, raid_value_active, standby_slot_number, raid_value_standby)) check_failure_code(raid_value_active, raid_value_standby)
def installImages_7_x (): # Check ifbios upgrade is needed poap_log(poap_script_log_handler, "Checking if bios upgrade is needed") if(is_bios_upgrade_needed()): poap_log(poap_script_log_handler, "##############Installing new BIOS(will take upto 5 minutes dont abort)S############") install_bios() try: poap_log(poap_script_log_handler, "Installing system image") global system_image_dst, poap_script_log_handler timeout = -1 try: cli ("config terminal ; boot nxos %s" % system_image_dst) except SyntaxError: poap_log(poap_script_log_handler, "WARNING: set boot variable system failed") poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) cleanup_files() poap_script_log_handler.close() exit(1) command_successful = False timeout = 10 # minutes first_time = time.time() endtime = first_time + timeout * 60 #sec per min retry_delay = 30 # seconds while not command_successful: new_time = time.time() try: cli ("copy running-config startup-config") command_successful = True except SyntaxError: poap_log(poap_script_log_handler, "WARNING: copy run to start failed") poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) if new_time > endtime: poap_log(poap_script_log_handler, "ERROR: time out waiting for \"copy run start\" to complete successfully") sys.exit(-1) poap_log(poap_script_log_handler, "WARNING: retry in 30 seconds") time.sleep( retry_delay ) poap_log(poap_script_log_handler, "INFO: Configuration successful") except Exception as inst: poap_log(poap_script_log_handler, "Install images failed : %s " % inst) cleanup_files() poap_script_log_handler.close() exit(1)
def main(): """ Function to fix Cisco Bug CSCur33701 """ # # Loop for Main output # eidlist1 = eidlist() for eid in eidlist1: eidrib = lisp_rib(eid) eidfib = lisp_fib(eid) for fib in eidfib: if fib != eidrib: cisco.cli('clear ip route ' + eid) print "LISP EID {} - Found RIB-FIB out of sync and fixed".format(eid) else: continue
def install_certificates(): """ Will install the certificates on the box """ for file in os.listdir( os.path.join("/bootflash", options['destination_path'])): if file.endswith(".pem"): certificate = os.path.join(options["destination_path"], file) poap_log("Certificate is %s" % (certificate)) add_trustpoint_op = cli( "configure terminal ; crypto ca trustpoint __securePOAP_trustpoint ; exit" ) poap_log("Add output %s" % (add_trustpoint_op)) install_op = cli( "configure terminal ; crypto ca authenticate __securePOAP_trustpoint pemfile bootflash:%s" % (certificate)) poap_log("Install output: %s" % (install_op))
def trustpoint_already_present(): cmd = "configure terminal ; show crypto ca trustpoints" poap_log("Executing %s" % (cmd)) ca_check = cli(cmd) if '__securePOAP' in ca_check: return True return False
def get_bios_ver(): msg = cli ("show version") lines = msg[1].split("\n") for line in lines: index=line.find("BIOS:") if (index!=-1): index=line.find("version") ver=line[index+8:index+13] return ver
def lisp_rib(eid_IP): """ Function to provide RIB output interface """ eid1 = cisco.cli('show ip route ' + eid_IP + ' | in \*via') eid2 = eid1.split(',') eid3 = [x.strip(' ') for x in eid2] eid = eid3[1] return eid
def get_ARP_Table(ipaddr): arpCmd = 'sh ip arp ' + ipaddr arpCmdResult = cisco.cli(arpCmd) arpCmdResultList = arpCmdResult.split('\n') for arp in arpCmdResultList: if (-1<arp.find(args.ip)): return arp else: print ' %s : Not found IP Address Infomation' % args.ip sys.exit()
def get_Interface_info(): macCmd = 'sh mac address-table addr ' + IP_info[MAC] macCmdResult = cisco.cli(macCmd) macCmdResultList = macCmdResult.split('\n') for infInfo in macCmdResultList: idx = infInfo.find(IP_info[MAC]) if(-1<idx): IP_info[Intf] = infInfo[58:] get_Description_info(IP_info[Intf]) break
def get_Description_info(iInfo): if(iInfo.find('Eth') == 0 or iInfo.find('Po')==0): intCmd = 'sh int desc | inc ' + iInfo if(vCheck.NexusVersion==vCheck.N7K): intCmdResult = cisco.cli(intCmd) intCmdResultList = intCmdResult.split('\n') if(intCmdResult != ''): IP_info[Desc] = intCmdResultList[0][25:].strip() elif(vCheck.NexusVersion==vCheck.N5K): intCmdResult = cisco.CLI(intCmd, False) intCmdResultList = intCmdResult.get_output() if(intCmdResult != ''): IP_info[Desc] = intCmdResultList[0][25:].strip()
def eidlist(): """ Gathering LISP EIDs by line of 'show lisp eid sum' output """ eidlist = [] eidlist1 = cisco.cli('sh lisp dyn sum | ex Dyn-EID | ex VRF | ex Packet') eidlist2 = str(eidlist1) eidlist3 = eidlist2.split('\n')[:-1] for x in eidlist3: y = x.split(" ") z = filter(None, y) zz = z[1] eidlist.append(zz) return eidlist
def extractBootVar (): global system_image_saved, kickstart_image_saved poap_log(poap_script_log_handler, "show boot") bootOutput = cli ("show boot") bootOutArray = bootOutput[1].split("\n") bootRaw = bootOutArray[3].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') kickstart_image_saved = bootlist[1] bootRaw = bootOutArray[4].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') system_image_saved = bootlist[1] poap_log(poap_script_log_handler, "Boot variables: kickstart:%s, system:%s" % (kickstart_image_saved, system_image_saved)) return
def get_version (): msg = cli ("show version") lines = msg[1].split("\n") for line in lines: index=line.find("kickstart:") if (index!=-1): index=line.find("version") ver=line[index+8:] return ver index=line.find("system:") if (index!=-1): index=line.find("version") ver=line[index+8:] return ver
def setSrcCfgFileNameLocation(): global config_file_src, poap_script_log_handler, env startAppend = 0 timeout = -1 poap_log(poap_script_log_handler, "show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutput = cli ("show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutArray = cdpOutput[1].split("\n") cdpRaw = cdpOutArray[7].split() cdpRawIntf = cdpOutArray[len(cdpOutArray) - 2].split() cdplist = cdpRaw[0].split('(') switchName = cdplist[0] intfName = cdpRawIntf[len(cdpRawIntf) - 1] config_file_src = "conf_%s_%s.cfg" % (switchName, intfName) config_file_src = string.replace(config_file_src, "/", "_") poap_log(poap_script_log_handler, "Selected conf file name : %s" % config_file_src)
def get_Interface_info(): macCmd = 'sh mac address-table addr ' + IP_info[MAC] macCmdResultList = [] if(vCheck.NexusVersion==vCheck.N7K): macCmdResult = cisco.cli(macCmd) macCmdResultList = macCmdResult.split('\n') elif(vCheck.NexusVersion==vCheck.N5K): macCmdResult = cisco.CLI(macCmd, False) macCmdResultList = macCmdResult.get_output() for infInfo in macCmdResultList: idx = infInfo.find(IP_info[MAC]) if(-1<idx): IP_info[Intf] = infInfo[58:] get_Description_info(IP_info[Intf]) break
def get_ARP_Table(ipaddr): arpCmd = 'sh ip arp ' + ipaddr arpCmdResultList = [] if(vCheck.NexusVersion==vCheck.N7K): arpCmdResult = cisco.cli(arpCmd) arpCmdResultList = arpCmdResult.split('\n') elif(vCheck.NexusVersion==vCheck.N5K): arpCmdResult = cisco.CLI(arpCmd, False) arpCmdResultList = arpCmdResult.get_output() for arp in arpCmdResultList: if (-1<arp.find(args.ip)): return arp else: print ' %s : Not found IP Address Infomation' % args.ip sys.exit()
def extractBootVar(): global system_image_saved, kickstart_image_saved poap_log(poap_script_log_handler, "show boot") bootOutput = cli("show boot") bootOutArray = bootOutput[1].split("\n") bootRaw = bootOutArray[3].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') kickstart_image_saved = bootlist[1] bootRaw = bootOutArray[4].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') system_image_saved = bootlist[1] poap_log( poap_script_log_handler, "Boot variables: kickstart:%s, system:%s" % (kickstart_image_saved, system_image_saved)) return
def setSrcCfgFileNameLocation(): global config_file_src, poap_script_log_handler, env startAppend = 0 timeout = -1 poap_log(poap_script_log_handler, "show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutput = cli("show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutArray = cdpOutput[1].split("\n") cdpRaw = cdpOutArray[7].split() cdpRawIntf = cdpOutArray[len(cdpOutArray) - 2].split() cdplist = cdpRaw[0].split('(') switchName = cdplist[0] intfName = cdpRawIntf[len(cdpRawIntf) - 1] config_file_src = "conf_%s_%s.cfg" % (switchName, intfName) config_file_src = string.replace(config_file_src, "/", "_") poap_log(poap_script_log_handler, "Selected conf file name : %s" % config_file_src)
def installImages (): try: poap_log(poap_script_log_handler, "Installing kickstart and system images") global kickstart_image_dst, system_image_dst, poap_script_log_handler timeout = -1 poap_log(poap_script_log_handler, "######### Copying the boot variables ##########") try: cli ("config terminal ; boot kickstart %s" % kickstart_image_dst) except SyntaxError: poap_log(poap_script_log_handler, "WARNING: set boot variable kickstart failed") poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) cleanup_files() poap_script_log_handler.close() exit(1) try: cli ("config terminal ; boot system %s" % system_image_dst) except SyntaxError: poap_log(poap_script_log_handler, "WARNING: set boot variable system failed") poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) cleanup_files() poap_script_log_handler.close() exit(1) command_successful = False timeout = 10 # minutes first_time = time.time() endtime = first_time + timeout * 60 #sec per min retry_delay = 30 # seconds while not command_successful: new_time = time.time() try: cli ("copy running-config startup-config") command_successful = True except SyntaxError: poap_log(poap_script_log_handler, "WARNING: copy run to start failed") poap_log(poap_script_log_handler, "********** Traceback **********\n %s" % traceback.format_exc()) if new_time > endtime: poap_log(poap_script_log_handler, "ERROR: time out waiting for \"copy run start\" to complete successfully") sys.exit(-1) poap_log(poap_script_log_handler, "WARNING: retry in 30 seconds") time.sleep( retry_delay ) poap_log(poap_script_log_handler, "INFO: Configuration successful") except Exception as inst: poap_log(poap_script_log_handler, "Install images failed : %s " % inst) cleanup_files() poap_script_log_handler.close() exit(1)
def extract_cdp_info(): #cli | xml raw = cli('show cdp neighbors | xml | exclude "]]>]]>"') # Load and parse XML tree = ET.ElementTree(ET.fromstring(raw)) data = tree.getroot() cdp_info = '{http://www.cisco.com/nxos:6.2.5.:cdpd}' for i in data.iter(cdp_info + 'ROW_cdp_neighbor_brief_info'): #parse interface, port and platform info from xml output intf_id = i.find(cdp_info + 'intf_id').text port_id = i.find(cdp_info + 'port_id').text platform_id = i.find(cdp_info + 'platform_id').text #save the info in a dictionary if intf_id not in cdp_dict: cdp_dict[intf_id] = {} cdp_dict[intf_id]['intf_id'] = intf_id cdp_dict[intf_id]['platform_id'] = platform_id cdp_dict[intf_id]['port_id'] = port_id
def lisp_fib(eid_IP): """ Function to provide FIB output interface """ modules = 18 eid_fiblist = [] while modules != 0: modules -= 1 try: module = str(modules) eid1 = cisco.cli('show forwarding route ' + eid_IP + ' module ' + module + ' | in ' + eid_IP) eid_fib1 = eid1.split('\n') for x in eid_fib1: y = x.split(" ") z = filter(None, y) eid_fib = z[2] eid_fiblist.append(eid_fib) return eid_fiblist except: pass return eid_fiblist
def copy_certificates(): ''' 2 separate dest_path variables are required as shutil & os modules understand paths as linux paths, while copy cli requires path in format of bootflash:<path> ''' license_found = "" dest_path = "/".join(["/bootflash", options["destination_path"]]) shutil.rmtree(dest_path, ignore_errors=True) poap_log("Path is %s" % (dest_path)) poap_log( "Removing the destination directory to prevent installation of malicious certificates" ) os.makedirs(dest_path) os.chmod(dest_path, 0o777) #if os.environ.get("POAP_PHASE", None) == "USB": if True: for file in os.listdir("/usbslot%s" % (options["usb_slot"])): if file.endswith(".pem"): license_found = True usb_string = ("usb%s" % (options["usb_slot"])) cert = file copy_src = ":".join([usb_string, cert]) dest_path = ":".join( ["bootflash", options["destination_path"]]) poap_log("Copying from %s to %s" % (copy_src, dest_path)) cmd = ("copy %s %s" % (copy_src, dest_path)) cmd = ("configure terminal ; terminal dont-ask ; copy %s %s" % (copy_src, dest_path)) poap_log("Formed cmd string: %s" % (cmd)) cp_op = cli(cmd) if not license_found: poap_log("No license on USB drive. Please check.") abort("No license on USB drive. Please check.") else: poap_log("Invalid Environment. Environment is not USB. ") abort("Invalid Environment. Environment is not USB.")
def setSrcCfgFileNameLocation(): try: poap_log(poap_script_log_handler, "Setting source cfg filename") global config_file_src, poap_script_log_handler, env startAppend = 0 timeout = -1 poap_log(poap_script_log_handler, "show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutput = cli ("show cdp neighbors interface %s" % os.environ['POAP_INTF']) cdpOutArray = cdpOutput[1].split("\n") cdpRaw = cdpOutArray[7].split() cdpRawIntf = cdpOutArray[len(cdpOutArray) - 2].split() cdplist = cdpRaw[0].split('(') switchName = cdplist[0] intfName = cdpRawIntf[len(cdpRawIntf) - 1] config_file_src = "conf_%s_%s.cfg" % (switchName, intfName) config_file_src = string.replace(config_file_src, "/", "_") poap_log(poap_script_log_handler, "Selected conf file name : %s" % config_file_src) except Exception as inst: poap_log(poap_script_log_handler, "Set src config filename location failed : %s " % inst) cleanup_files() poap_script_log_handler.close() exit(1)
def extractBootVar (): try: poap_log(poap_script_log_handler, "Extract kickstart and system images from \"show boot\"") global system_image_saved, kickstart_image_saved poap_log(poap_script_log_handler, "show boot") bootOutput = cli ("show boot") bootOutArray = bootOutput[1].split("\n") bootRaw = bootOutArray[3].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') kickstart_image_saved = bootlist[1] bootRaw = bootOutArray[4].split('=') if len(bootRaw) == 2: bootlist = bootRaw[1].split(':') system_image_saved = bootlist[1] poap_log(poap_script_log_handler, "Boot variables: kickstart:%s, system:%s" % (kickstart_image_saved, system_image_saved)) return except Exception as inst: poap_log(poap_script_log_handler, "Extract bootvar failed : %s " % inst) cleanup_files() poap_script_log_handler.close() exit(1)
def add_description(): for key, value in cdp_dict.items(): if 'port_id' in value and 'platform_id' in value and 'intf_id' in value: cli("conf t ") cli('interface ' + value['intf_id'] + ' ; description ' + value['platform_id'] + ' ' + value['port_id'])
Device-ID Local Intrfce Hldtme Capability Platform Port ID SW-JWALA-ECBU-KK23 mgmt0 142 S I WS-C2950-24 Fas0/6 Lotos-PE1(JAF1817AMLJ) Eth7/5 154 R S s N7K-C7009 Eth7/2 Lotos-PE2(JAF1817AMLJ) Eth7/6 132 R S s N7K-C7009 Eth7/4 Lotos-PE3(JAF1817AMLJ) Eth7/7 169 R S s N7K-C7009 Eth7/9 Total entries displayed: 4 """ # Execute the command on the switch raw_input = cli("show cdp neighbors") # Split the output into a list containing each line all_raw_lines = raw_input.split("\n") # print all_raw_lines # We need to ignore the first few lines, including the header of the table. This # code does that all_device_lines = [] line_no = 0 dev_list = {} for line in all_raw_lines: line_no += 1 if line_no <= 6:
Device-ID Local Intrfce Hldtme Capability Platform Port ID SW-JWALA-ECBU-KK23 mgmt0 142 S I WS-C2950-24 Fas0/6 Lotos-PE1(JAF1817AMLJ) Eth7/5 154 R S s N7K-C7009 Eth7/2 Lotos-PE2(JAF1817AMLJ) Eth7/6 132 R S s N7K-C7009 Eth7/4 Lotos-PE3(JAF1817AMLJ) Eth7/7 169 R S s N7K-C7009 Eth7/9 Total entries displayed: 4 ''' # Execute the command on the switch raw_input = cli("show cdp neighbors") # Split the output into a list containing each line all_raw_lines = raw_input.split('\n') #print all_raw_lines # We need to ignore the first few lines, including the header of the table. This # code does that all_device_lines = [] line_no = 0 dev_list = {} for line in all_raw_lines: line_no += 1 if line_no <= 6: pass
# Python #Example of using python Cisco api on nexus 3000. #Bwahrmann 5-2015 #import cisco modules import cisco # The cisco module must be called in order to use the CLI class "cisco.CLI" = module.class # displaying router info host = cisco.cli('show run | i hostname') processor = cisco.cli('show version | i Processor') kick = cisco.cli('show version | i kickstart',) print "\nRouter info :\n%s%s%s\n\n" %(host, processor, kick) # display boot flash print "Bootflash Info:\n" dirboot = cisco.cli('dir bootflash:','do_print') print "****************************************************************\n\n" print " Start of file transfer" # file transfer script tsf = cisco.transfer(protocol='tftp', host='10.255.40.101', source='/SDN/SDN_Programming_Fundamentals/ftp/n3000-uk9.6.0.2.U3.7.bin_sdnclass02', dest='bootflash:n3000-uk9.6.0.2.U3.7.bin_sdnclass02', vrf='management', login_timeout=10, user='******', password='******') #verify file in bootflash: print "Bootflash Info:\n"
single_image_poap_flag = 0 # copy config file and images copyConfig() # copy config file and images copySystem() if single_image_poap_flag != 1 : copyKickstart() signal.signal(signal.SIGTERM, sig_handler_no_exit) # install images if single_image_poap_flag != 1 : installImages() else: installImages_7_x() if emptyFirstFile is 0: cli ('copy bootflash:%s scheduled-config' % config_file_dst_first) poap_log(poap_script_log_handler, "######### Copying the first scheduled cfg done ##########") #removeFile("/bootflash/%s" % config_file_dst_first) cli ('copy bootflash:%s scheduled-config' % config_file_dst_second) poap_log(poap_script_log_handler, "######### Copying the second scheduled cfg done ##########") removeFile("/bootflash/%s" % config_file_dst_second) poap_script_log_handler.close() exit(0)
# source interface_rate.py # # This script was tested on N7K using 6.2(5) release. # from __future__ import division from cisco import cli import sys import xml.etree.cElementTree as ET # Get interface information in XML format print print 'Collecting and processing interface statistics ...' print sys.stdout.flush() raw = cli('show interface | xml | exclude "]]>]]>"') # Load and parse XML tree = ET.ElementTree(ET.fromstring(raw)) data = tree.getroot() # Find and display interface rate information if_manager = '{http://www.cisco.com/nxos:6.2.5.:if_manager}' table = "{0:16}{1:9}{2:9}{3:9}{4:9}{5:9}{6:9}{7:9}" print '---------------------------------------------------------------------------' print table.format("Port", "Intvl", "Rx Mbps", "Rx %", "Rx pps", "Tx Mbps", "Tx %", "Tx pps") print '---------------------------------------------------------------------------' for i in data.iter(if_manager + 'ROW_interface'): try: interface = i.find(if_manager + 'interface').text
def set_hostname(hostname): cisco.cli('conf t') cisco.cli('hostname %s' % hostname)
print "Error: Missing argument, need either 'up' or 'down'" exit() if sys.argv[1] == "up": # At this point we should have a file containing ports to bring up. if os.path.isfile(hostlistfile) == False: print "No hostlist found, exiting" exit() file = open(hostlistfile, "r") line = file.readline() while line != "": stripped = line.rstrip('\n') cli("config terminal ; interface %s ; no shutdown" % stripped) print "Bringing up interface %s" % stripped line = file.readline() #We are now done with the hostlist file, lets delete. os.remove(hostlistfile) if sys.argv[1] == "down": # Uplinks are not yet up, lets see which hosts are active, bring those # down and save to a file.
# # 1. Copy script to NX-OS switch bootflash: # 2. Execute using 'python bootflash:interface_rate.py # from __future__ import division import cisco import sys import xml.etree.cElementTree as ET # Get interface information in XML format print print 'Collecting and processing interface statistics ...' print sys.stdout.flush() raw = cisco.cli('show interface | xml | exclude "]]>]]>"', False)[1] # Load and parse XML tree = ET.ElementTree(ET.fromstring(raw)) data = tree.getroot() # Find and display interface rate information if_manager = '{http://www.cisco.com/nxos:1.0:if_manager}' table = "{0:16}{1:9}{2:9}{3:9}{4:9}{5:9}{6:9}{7:9}" print '---------------------------------------------------------------------------' print table.format("Port", "Intvl", "Rx Mbps", "Rx %", "Rx pps", "Tx Mbps", "Tx %", "Tx pps") print '---------------------------------------------------------------------------' for i in data.iter(if_manager + 'ROW_interface'): try: interface = i.find(if_manager + 'interface').text bw = int(i.find(if_manager + 'eth_bw').text)
import sys import time from cisco import cli from cisco import clip # v2.1 # Authors: Shaun Gomez & John Senkow # Clear all multicast state for given group on NXOS # Python 2.7 mcast_g = str(sys.argv[1]) cli("clear ip igmp groups " + mcast_g) cli("clear ip pim route " + mcast_g) cli("clear ip mroute data-created " + mcast_g) cli("clear ip netstack mroute " + mcast_g) print 'All Multicast State Cleared For:' print mcast_g print 'Verification of State Clear, Please Wait 3 Seconds to Complete' for verify_print in xrange(3, 0, -1): time.sleep(1) print verify_print clip("show ip igmp groups " + mcast_g) clip("show ip igmp route " + mcast_g) clip("show ip mroute " + mcast_g) clip("show ip pim route " + mcast_g) print "Verification Complete"
def set_hostname_improved(hostname): cisco.cli('conf t') cisco.cli('hostname %s' % hostname)
# source interface_rate.py # # This script was tested on N7K using 6.2(5) release. # from __future__ import division from cisco import cli import sys import xml.etree.cElementTree as ET # Get interface information in XML format print print 'Collecting and processing interface statistics ...' print sys.stdout.flush() raw = cli('show interface | xml | exclude "]]>]]>"') # Load and parse XML tree = ET.ElementTree(ET.fromstring(raw)) data = tree.getroot() # Find and display interface rate information if_manager = '{http://www.cisco.com/nxos:6.2.5.:if_manager}' table = "{0:16}{1:9}{2:9}{3:9}{4:9}{5:9}{6:9}{7:9}" print '---------------------------------------------------------------------------' print table.format("Port", "Intvl", "Rx Mbps", "Rx %", "Rx pps", "Tx Mbps", "Tx %", "Tx pps") print '---------------------------------------------------------------------------' for i in data.iter(if_manager + 'ROW_interface'): try: interface = i.find(if_manager + 'interface').text bw = int(i.find(if_manager + 'eth_bw').text)
def critical_code(): with RollBack('critical'): cisco.cli('conf t') cisco.cli('int po 1337') raise cisco.cli_execution_error cisco.cli('ip add 1.1.1.1/24')
def main(): set_hostname('saves') print 'hostname saves' == cisco.cli('show start | grep hostname') set_hostname_improved('saves-improved') print 'hostnames saves-improved' == cisco.cli('show start | grep hostname')
def expandrange(rangefunc,stepcnt): hosts = [] step = str(stepcnt[0]) octets = rangefunc.split('.') for i,octet in enumerate(octets): if '-' in octet: octetrange = octet.split('-') sip = int(octetrange[0]) dip = int(octetrange[1]) for digit in range(int(octetrange[0]),int(octetrange[1])+1, int(step) if i==3 else 1): ip = '.'.join(octets[:i] + [str(digit)] + octets[i+1:]) hosts += expandrange(ip,stepcnt) break else: if checkRange(rangefunc): hosts.append(rangefunc) return hosts parser = ArgumentParser('AdvPing') parser.add_argument('ip', help='IP range to ping, e.g., 10.1.0-1.0-255 will expand to 10.1.0.0/23') parser.add_argument('options', type=str, default=['1'], nargs='*', help='Options to pass to ping') args = parser.parse_args() targets = expandrange(args.ip,args.options) for ip in targets: tupleping = cisco.cli('ping %s' % ip) strping = str(tupleping) m = re.search('([0-9\.]+)% packet loss',strping ) print('%s - %s' % (ip, 'UP' if float(m.group(1)) == 0.0 else 'DOWN'))
#!/usr/bin/env python## Copyright (C) 2013 Cisco Systems Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.### This script is a simple 'supercommand', where a sequence of three# common commands, show ip arp, show mac address-table and show cdp neighbor# are all chained with their outputs fed into each other to gather information# about a particular device connected to this switch.## The logic here can be extended to include additional commands, and introduce# branching logic to handle different situations. An example may be to treat a# host that appears in the CDP table differently from one that does not, and# collect a other command outputs in that case## Tested and validated on Nexus 9000 6.1(2)I2(2a)## A best effort was also made to try to run it on other platforms, but was only# tested on Nexus 5000 5.2(1)N1(6)## For Nexus 5000 support, this depends on xmltodict# https://github.com/martinblech/xmltodict/blob/master/xmltodict.py##import reimport pprintimport jsonfrom argparse import ArgumentParser ## This entire block of code is aimed at detecting of we have access to cli and# the clid command. If we do not have them, we attempt to import cli from the# cisco package (which is present on other NXOS platforms). If that fails, we# cannot proceed further. However, if it does succeed, then we need to create# an equivalent of clid(), so we introduce an external dependency on xmltodict# which is used to convert the XML output of the commands into a JSON dict.## Finally, after that we check to see if cli() returns a tuple, if so that means# we are on a 5K or similar, and we need to patch the output to return it as# just the command output, and not the two-tuple class UnstructuredOutput(Exception): pass try: from cli import clid, cliexcept ImportError: try: from cisco import cli except ImportError: print 'Script is unsupported on this platform' raise def clid(cmd): try: import xmltodict except ImportError: print 'Script is unsupported on this platform: requires xmltodict' raise tag = '__readonly__' starttag, endtag = '<' + tag + '>', '</' + tag + '>' output = cli('{0} | xml'.format(cmd)) start_index, end_index = output.find(starttag), output.find(endtag) if start_index == -1 or end_index == -1: raise UnstructuredOutput( 'Command {0} does not support structured output: {1}'.format( cmd, output)) output = xmltodict.parse( output[start_index:end_index + len(endtag)]) json_output = json.dumps(output[tag]) return json_output def cli_decorator(target_function): def wrapper(cmd): return target_function(cmd)[1] return wrapper if isinstance(cli('show version'), tuple): cli = cli_decorator(cli) def findkey(dct, key, value=None): found = [] if isinstance(dct, list): for item in dct: f = findkey(item, key, value) if f: found.extend(f) if isinstance(dct, dict): for k, v in dct.items(): if isinstance(v, list) or isinstance(v, dict): f = findkey(v, key, value) if f: found.extend(f) if str(k) == str(key): if (value and str(v) == str(value)) or not value: found.append(v) return found if len(found) > 0 else None def getarpentry(ip=None, vrf='all'): # Check the output of the ARP table for the IP address in question if ip: arpoutput = json.loads(clid('show ip arp {0} vrf {1}'.format(ip, vrf))) else: arpoutput = json.loads(clid('show ip arp vrf {0}'.format(vrf))) rowadjlist = findkey(arpoutput, 'ROW_adj') if not rowadjlist: return None # flatten out the data received from show ip arp into a list of dicts arpentries = [] # print "TITU : ", arpoutput for rowadj in rowadjlist: if isinstance(rowadj, dict): arpentries.append(rowadj) elif isinstance(rowadj, list): arpentries.extend(rowadj) arplist = [] for arp in arpentries: try: # print "TITU Int : ", arp['intf-out'] arplist.append( [arp['ip-addr-out'], arp['time-stamp'], arp['mac'], arp['intf-out']]) except KeyError: continue return arplist def getmacentry(mac, vlanfilter=None): try: macaddroutput = json.loads( clid('show mac address-table address {0}'.format(mac))) except UnstructuredOutput: return None macaddrlist = findkey(macaddroutput, 'ROW_mac_address') if not macaddrlist: return None macentries = [] for macaddr in macaddrlist: if isinstance(macaddr, dict): macentries.append(macaddr) elif isinstance(macaddr, list): macentries.extend(macaddr) entries = [] # print "TITU:mac, ", mac # print "TITU: ", macaddroutput # print "TITU", macentries for macaddr in macentries: vlan = macaddr['disp_vlan'] mac = macaddr['disp_mac_addr'] entrytype = macaddr['disp_type'] age = macaddr['disp_age'] secure = macaddr['disp_is_secure'] ntfy = macaddr['disp_is_ntfy'] port = macaddr['disp_port'] # print "TITU", port if vlanfilter and vlan != vlanfilter: continue # If a MAC is on a port channel, dereference it and use the first entry if 'po' in port.lower(): members = getportchannelmembers(port) if not members: raise Exception( 'Unable to find any member interfaces in {0}'.format(port)) entries.extend( [[vlan, mac, entrytype, age, secure, ntfy, memberport, port] for memberport in members]) elif 'vlan' in port.lower(): continue else: entries.append( [vlan, mac, entrytype, age, secure, ntfy, port, port]) return entries def getportchannelmembers(port): po = json.loads( clid('show port-channel summary int {0}'.format(port))) members = findkey(po, 'port') return members def getcdpentry(port): # Next use the interface we found the device on from CAM and look it up in # CDP cdp = json.loads(clid('show cdp neighbor interface {0}'.format(port))) cdp = findkey(cdp, 'ROW_cdp_neighbor_brief_info') if not cdp: raise Exception('Unable to find {0} in CDP output'.format(port)) if len(cdp) > 0: cdp = cdp[0] return cdp def main(): # Perform some basic argument parsing for parameters passed to the script parser = ArgumentParser('Supercommand') parser.add_argument( 'ip', help='IP address to query. Use all for every IP in arp') args = parser.parse_args() ip = args.ip