def main(): try: deploy_startup_config() # deploy_boot_images() except Exception as e: poap_log("Deploy startup or boot failed") poap_log_close() # Don't swallow exceptions otherwise the Cisco switch will think the POAP was a success # and proceed to boot rather than retrying raise e # Copying to scheduled-config is necessary for POAP to exit on the next # reboot and apply the configuration. We want to merge the running-config # changes made by both the startup-config deployment # and the boot image deployment. # The issue is if we copy to scheduled-config MORE THAN ONCE it will # trigger POAP/config application MORE THAN ONCE as well, which we don't want. # So we have to do all these operations in the same script, that way they # are not order-dependant. try: poap_log("Removing {0}".format(tmp_config_path_unix)) os.remove(tmp_config_path_unix) except: poap_log("Removing {0} failed".format(tmp_config_path_unix)) #poap_log("From: %s to %s" % ("running-config", "startup-config")) #cli("copy running-config startup-config") poap_log("From: %s to %s" % ("startup-config", tmp_config_path)) cli("copy startup-config %s" % tmp_config_path) poap_log("From: %s to %s" % (tmp_config_path, "scheduled-config")) cli("configure terminal ; copy %s scheduled-config" % tmp_config_path) poap_log_close()
def protocol_check(): u"""Checking running protocols""" cmd_lldp = "show feature | egrep lldp" proto_lldp = re.findall(r'enabled', cli.cli(cmd_lldp)) cmd_cdp = "show cdp global | sed -n 2p" proto_cdp = re.findall(r'enabled', cli.cli(cmd_cdp)) proto = {"cdp":str(proto_cdp), "lldp":str(proto_lldp)} counter = 2 print ('\nChecking CDP/LLDP protocols...') for key, value in proto.items(): try: if re.search(r'enabled', value): print (key.upper() + ' protocol is' + color.GREEN +' enabled' + color.ENDCOLOR) if key == 'cdp': counter = counter + 1 elif key == 'lldp': counter = counter - 1 else: counter = 0 print (key.upper() + ' protocol is' + color.RED + ' disabled' + color.ENDCOLOR) except AttributeError: print ('Check device. Need to be Nexus 7000/9000.') return counter
def print_line (text, step=None, width=40): stext="({})".format(step) if step else "***" if step: print "\n" print "***{}*** {} {}".format(stext, text, "*"*(width-len(text))) print_line("Checking hardware", 1) cli.executep("show platform | i Model|C9200|--\ ") print_line("Checking IOS version", 2) cli.executep("show version | i IOS XE") print_line("Generating RSA key", 3) cli.configurep("crypto key generate rsa modulus 2048 label sshv2logincert") print_line("Obtaining serial number", 4) license = cli.cli("show license udi") sn = license.split(":")[3].rstrip() print_line("Serial number is {}".format(sn)) print_line("Disabling copy prompts", 5) cli.configure("file prompt quiet") print_line("Copying configuration file from TFTP server", 6) cli_command = "copy tftp://{}/config/{}.txt startup-config vrf Mgmt-vrf".format (tftp_server, sn.lower()) cli.executep(cli_command) time.sleep (5) print_line("Verifying received startup config...", 7) host_line=cli.cli("show startup-config | i hostname").split() # actual output will be "Using xxxx out of 2097152 byteshostname sw9200-1A" if host_line: host_name=host_line[-1] # last entry print_line("Configuration for {} downloaded successfully!".format(host_name)) print_line("Rebooting with the new config!", 8) cli.cli("reload") else: print("*** *** *** Configuration failed *** *** ***")
def incomingConnexion(self, clientSocket, address): """ function to handle incoming connexion once received """ self.sendText(clientSocket, "Welcome to your Home\n\n") self.sendText(clientSocket, " _|=|__________\n") self.sendText(clientSocket, " / \\\n") self.sendText(clientSocket, " / \\\n") self.sendText(clientSocket, " /__________________\\\n") self.sendText(clientSocket, " || || /--\ || ||\n") self.sendText(clientSocket, " ||[]|| | .| ||[]||\n") self.sendText(clientSocket, " ()||__||_|__|_||__||()\n") self.sendText(clientSocket, "( )|-|-|-|====|-|-|-|( ) \n") self.sendText(clientSocket, "^^^^^^^^^^====^^^^^^^^^^^\n\n") self.sendText(clientSocket, "Please login to access your home\n\n") auth = False fail = 0 while not auth: auth = self.auth(clientSocket, address) if not auth: #if auth failed fail = fail + 1 #increase fail count self.sendText(clientSocket, "Invalid login please try again\n\n") if fail >= self.__maxFailedLogin: #if failed limit exceed self.sendText(clientSocket, "Too many failed attempt\n") self.sendText(clientSocket, "Goodbye") self.killClient(clientSocket) #send to CLI cli.cli(clientSocket, self.__adminName, address)
def configure_smart_licensing(idtoken, throughput): license_status = False throughput_status = False if idtoken is None: logger.warning("idtoken value is None. Please provide valid idtoken") return False smart_licensing_configuration = ''' license smart transport smart license smart url smart https://smartreceiver.cisco.com/licservice/license ''' logger.info("Trying to configure smart licensing. Configs: {}".format(smart_licensing_configuration)) for i in range(5): cli.configurep(smart_licensing_configuration) cli.executep('license smart trust idtoken {} local'.format(idtoken)) cli.configurep('platform hardware throughput level MB {}'.format(throughput)) output = cli.cli('show license tech support | inc ENABLED') if "Smart Licensing is ENABLED" in output: logger.info("Smart licensing successful") license_status = True output = cli.cli('sh platform hardware throughput level') logger.info("Throughput level set to: {}".format(output)) if str(throughput) in output: logger.info("Throughput level set successfully") throughput_status = True if license_status and throughput_status: logger.info("Successfully configured Smart Licensing and Throughput level") return True logger.warning("There were some issues with configuring Smart Licensing which did not succeed after 5 attempts. Please review configuration") return False
def get_output(command): """Shows output from running the command or opening a file if cli library is not present Args: command: string, command to be run if tac.DEBUG is set or path of the file to open, otherwise Returns: string - command execution output """ if is_debug_environment(): dir_name = get_test_dir_argument() filename = '{}.txt'.format(command) full_path = os.path.join(dir_name, filename) if os.path.isfile(full_path): with open(full_path) as f: return f.read() raise IOError("File {} is not found".format(full_path)) else: import cli result = cli.cli(command) i = 0 # Occasionally, cli library returns an empty output, in this case we try multiple time while result.count('\n') <= 2 and i < 3: result = cli.cli(command) i += 1 return result
def getvm(vmhost, vminfo, hypervisor, local_port): u"""Getting VMs from hypervisors""" cmdip = 'ping '+ vmhost + ' count 1 ' cmdiprun = cli.cli(cmdip) ipa = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', cmdiprun)[0] cmdfunc = lambda x: cli.cli('run bash ssh root@' + ipa + ' ' + x ) if vminfo == 'xen': #get_uuid_cmd = 'xe vm-list power-state=running params=uuid | egrep -o "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"' get_uuid_cmd = 'xe vm-list params=uuid | egrep -o "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"' uuid = cmdfunc(get_uuid_cmd).split('\n') get_vm_name = "xe vm-list params=name-label | awk '{print $5}' " vm_names = cmdfunc(get_vm_name).split('\n\n\n') counter = 0 while counter < (len(uuid)-2): print ('{0:15} \t\t {1:28} {2:25} {3:10}'.format (vm_names[counter].ljust(1), uuid[counter].ljust(62) , hypervisor.ljust(30), local_port)) counter = counter + 1 elif vminfo == 'esx': get_uuid_cmd = "esxcli vm process list | egrep 'UUID' | awk -F ': ' '{print $2}'" uuid = cmdfunc(get_uuid_cmd).split('\n') get_vm_name = "esxcli vm process list | egrep 'Display Name' | awk -F ': ' '{print $2}'" vm_names = cmdfunc(get_vm_name).split('\n') counter = 0 while counter < (len(vm_names)-1): print ('{0:15} \t\t {1:28} {2:25} {3:10}'.format (vm_names[counter].ljust(1), uuid[counter].ljust(62) , hypervisor.ljust(30), local_port)) counter = counter + 1
def getvm(vmhost, vminfo, hypervisor, local_port): u"""Getting VMs from hypervisors""" cmdip = 'ping ' + vmhost + ' count 1 ' cmdiprun = cli.cli(cmdip) ipa = re.findall( r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', cmdiprun)[0] cmdfunc = lambda x: cli.cli('run bash ssh root@' + ipa + ' ' + x) if vminfo == 'xen': #get_uuid_cmd = 'xe vm-list power-state=running params=uuid | egrep -o "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"' get_uuid_cmd = 'xe vm-list params=uuid | egrep -o "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"' uuid = cmdfunc(get_uuid_cmd).split('\n') get_vm_name = "xe vm-list params=name-label | awk '{print $5}' " vm_names = cmdfunc(get_vm_name).split('\n\n\n') counter = 0 while counter < (len(uuid) - 2): print('{0:15} \t\t {1:28} {2:25} {3:10}'.format( vm_names[counter].ljust(1), uuid[counter].ljust(62), hypervisor.ljust(30), local_port)) counter = counter + 1 elif vminfo == 'esx': get_uuid_cmd = "esxcli vm process list | egrep 'UUID' | awk -F ': ' '{print $2}'" uuid = cmdfunc(get_uuid_cmd).split('\n') get_vm_name = "esxcli vm process list | egrep 'Display Name' | awk -F ': ' '{print $2}'" vm_names = cmdfunc(get_vm_name).split('\n') counter = 0 while counter < (len(vm_names) - 1): print('{0:15} \t\t {1:28} {2:25} {3:10}'.format( vm_names[counter].ljust(1), uuid[counter].ljust(62), hypervisor.ljust(30), local_port)) counter = counter + 1
def protocol_check(): u"""Checking running protocols""" cmd_lldp = "show feature | egrep lldp" proto_lldp = re.findall(r'enabled', cli.cli(cmd_lldp)) cmd_cdp = "show cdp global | sed -n 2p" proto_cdp = re.findall(r'enabled', cli.cli(cmd_cdp)) proto = {"cdp": str(proto_cdp), "lldp": str(proto_lldp)} counter = 2 print('\nChecking CDP/LLDP protocols...') for key, value in proto.items(): try: if re.search(r'enabled', value): print(key.upper() + ' protocol is' + color.GREEN + ' enabled' + color.ENDCOLOR) if key == 'cdp': counter = counter + 2 elif key == 'lldp': counter = counter - 1 else: #counter = 0 print(key.upper() + ' protocol is' + color.RED + ' disabled' + color.ENDCOLOR) except AttributeError: print('Check device. Need to be Nexus 7000/9000.') return counter
def bef_run(): now = time.localtime() st = "%04d%02d%02d_%02d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) cli("show interface status >> bootflash:cdp-history/%s_intStaNdesc.txt" % st) cli("show interface description >> bootflash:cdp-history/%s_intStaNdesc.txt" % st)
def log(message, severity): ''' this can also log to spark. need to check if a token is present :param message: :param severity: :return: ''' cli('send log %d "%s"' % (severity, message))
def lldpneigh(): u"""Getting LLDP neighbours information""" cmd = 'show lldp neighbors detail' infolist = ['System Description', 'Port Description', 'Management Address:', 'Local Port', 'System Name'] g = lambda x,y: cli.cli (cmd + ' | egrep \\"' + x + '\\"' + ' | awk \\"{print $' + str(y) + '}\\"' ) tuple1 = [] for idx, val in enumerate (infolist): if idx == 0: list1 = (cli.cli (cmd + ' | egrep \\"' + val + '\\"' + ' | sed \\"s/' + val + '//g\\"')).split('\n') tuple1.append(list1) #print list1 elif idx == 1: list2 = g(val,3).split('\n') tuple1.append(list2) elif idx ==2 : list3 = g(val,3).split('\n') tuple1.append(list3) elif idx == 3: list4 = g(val,4).split('\n') tuple1.append(list4) elif idx == 4: list5 = g(val,3).split('\n') tuple1.append(list5) patern = re.compile('xen|kvm|esx|ubuntu|vmware', re.IGNORECASE) i = 0 #vmlist = [xen,kvm] while i < (len(list1) - 1): if (re.search(patern, list1[i]) != None): #print list1[i] if (re.search('xen', list1[i], re.IGNORECASE) != None): #print re.search('xen', list1[i], re.IGNORECASE) vminfo = 'xen' elif (re.search('esx', list1[i], re.IGNORECASE) != None): #re.search('xen', list1[i], re.IGNORECASE) vminfo = 'esx' hyperv_patern = list1[i].split(': ')[0] + list1[i].split(': ')[1].split(' ')[0] hyperv = re.sub(u'[^A-Za-z\s]*', u'', hyperv_patern) portid = list2[i] ipaddr = list3[i] interf = list4[i] if not arg['virtualmachines']: print ('{0:15} \t\t {1:10} {2:25} {3:10} {4:15}'.format (hyperv.ljust(15), portid.ljust(29) , ipaddr.ljust(34), 'LLDP'.ljust(27), interf)) else: #print "Before continue, please copy next public key to your hypervisors. Or you will need to enter password:\n" #get_pub_key = 'run bash cat /var/home/admin/.ssh/id_rsa.pub' #cli.clip(get_pub_key)o bulshit(list5[i], vminfo) vminfo ='' i=i+1
def lldpneigh(): u"""Getting LLDP neighbours information""" cmd = 'show lldp neighbors detail' infolist = [ 'System Description', 'Port Description', 'Management Address:', 'Local Port', 'System Name' ] g = lambda x, y: cli.cli(cmd + ' | egrep \\"' + x + '\\"' + ' | awk \\"{print $' + str(y) + '}\\"') tuple1 = [] for idx, val in enumerate(infolist): if idx == 0: list1 = (cli.cli(cmd + ' | egrep \\"' + val + '\\"' + ' | sed \\"s/' + val + '//g\\"')).split('\n') tuple1.append(list1) #print list1 elif idx == 1: list2 = g(val, 3).split('\n') tuple1.append(list2) elif idx == 2: list3 = g(val, 3).split('\n') tuple1.append(list3) elif idx == 3: list4 = g(val, 4).split('\n') tuple1.append(list4) elif idx == 4: list5 = g(val, 3).split('\n') tuple1.append(list5) patern = re.compile('xen|kvm|esx|ubuntu|vmware', re.IGNORECASE) i = 0 while i < (len(list1) - 1): if (re.search(patern, list1[i]) != None): if (re.search('xen', list1[i], re.IGNORECASE) != None): vminfo = 'xen' elif (re.search('esx', list1[i], re.IGNORECASE) != None): vminfo = 'esx' hyperv_patern = list1[i].split(': ')[0] + list1[i].split( ': ')[1].split(' ')[0] hyperv = re.sub(u'[^A-Za-z\s]*', u'', hyperv_patern) portid = list2[i] ipaddr = list3[i] interf = list4[i] if not arg['virtualmachines']: print('{0:15} \t\t {1:10} {2:25} {3:10} {4:15}'.format( hyperv.ljust(15), portid.ljust(29), ipaddr.ljust(34), 'LLDP'.ljust(27), interf)) else: getvm(list5[i], vminfo, hyperv, portid) vminfo = '' i = i + 1
def write_logs(log_type, interface): # 사용자가 선택한 타입의 로그 작성 if log_type == 'a' or log_type == "d": write_file("sh_int_ethernet", cli("show interface ethernet %s" % interface)) if log_type == 'b' or log_type == "d": write_file( "sh_int_ethernet_detail", cli("show interface ethernet %s transceiver details" % interface)) if log_type == 'c' or log_type == "d": write_file("sh_tech_support_pktmgr", cli("show tech-support pktmgr"))
def renumber_stack(serials, serial): # find position of the correct switch #1 in the list index = serials.index(serial) index += 1 if index <> 1: log("Renumbering switch top of stack".format(index), 5) cli('test pnpa service stack renumber-tos {}'.format(index)) cli('reload') sys.exit(1) else: log('No need to renumber stack')
def get_serial(): try: show_version = cli('show version') except pnp._pnp.PnPSocketError: time.sleep(90) show_version = cli('show version') try: serial = re.search(r"System Serial Number\s+:\s+(\S+)", show_version).group(1) except AttributeError: serial = re.search(r"Processor board ID\s+(\S+)", show_version).group(1) return serial
def reschedule(seconds, diff): UPDATE_SCRIPT_FIRING_COMMANDS = """ event manager applet ACL-SYNC-CHECK event timer watchdog time %s action 1.0 cli command "enable" action 1.1 cli command "guestshell run /home/guestshell/reboot_conn.py """ configure(UPDATE_SCRIPT_FIRING_COMMANDS % (seconds)) if answer == False: log("Cannot Reach Headend",4) cli('test cellular 0/2/0 modem-power-cycle')
def send_syslog(message): """Sends a syslog message to the device with severity 6 Args: message (str): message to be sent Returns: None """ cli('send log facility PYTHON severity 6 mnemonics CONF_DIFF ' '{message}'.format(message=message))
def deploy_startup_config(): startup_config_uri = '<%= (hasOwnProperty("startupConfigUri") ? startupConfigUri : "" )%>' if not startup_config_uri: return try: os.remove(tmp_config_path_unix) except: pass cli("copy %s %s vrf management" % (startup_config_uri, tmp_config_path)) cli("copy %s running-config" % tmp_config_path)
def remove_config(command, size): if size == '': try: cli.cli('configure terminal ; no' + ' ' + command) except BaseException: logger.error('Failed to remove configuration') sys.exit(0) else: try: cli.cli('configure terminal ; no' + ' ' + command + ' ' + size) except BaseException: logger.error('Failed to remove configuration') sys.exit(0)
def teststarcluster(): print sys.path clustername = 'smallcluster' master = cli.cli( ['listmaster', clustername] ) if master==None: print "No cluster previously setup" start_cluster = cli.cli( ['start', clustername, '-c', '../amazon_aws.config' ] ) master_name = cli.cli( ['listmaster', clustername] ) if master_name: print "Successfully created a cluster with X nodes" else: print "Found a cluster with master name %s" %(master)
def main(): print '\n\n\n\n###### STARTING ZTP SCRIPT ######' print '\n*** Obtaining serial number of device.. ***' serial = get_serial() print '*** Setting configuration file variable.. ***' config_file = "{}.cfg".format(serial) print '\n*** Config file: %s ***' % config_file if upgrade_required(): print '\n*** Upgrade is required. Starting upgrade process.. ***\n' if check_file_exists(img_cat9k): if not verify_dst_image_md5(img_cat9k, img_cat9k_md5): print '\n*** Attempting to transfer image to switch.. ***' file_transfer(tftp_server, img_cat9k) if not verify_dst_image_md5(img_cat9k, img_cat9k_md5): raise ValueError('Failed Xfer') else: file_transfer(tftp_server, img_cat9k) if not verify_dst_image_md5(img_cat9k, img_cat9k_md5): raise ValueError('XXX Failed Xfer XXX') print '\n*** Deploying EEM upgrade script ***' deploy_eem_upgrade_script(img_cat9k) print '\n*** Performing the upgrade - switch will reboot ***\n' cli('event manager run upgrade') time.sleep(600) else: print '\n*** No upgrade is required!!! ***' # Cleanup any leftover install files print '\n*** Deploying Cleanup EEM Script ***' deploy_eem_cleanup_script() print '\n*** Running Cleanup EEM Script ***' cli('event manager run cleanup') time.sleep(30) if not check_file_exists(config_file): print '\n*** Xferring Configuration!!! ***' file_transfer(tftp_server, config_file) time.sleep(10) print '\n*** Removing any existing certs ***' find_certs() time.sleep(10) print '\n*** Deploying Configuration ***' try: configure_replace(config_file) configure('crypto key generate rsa modulus 4096') except Exception as e: pass print '\n###### FINISHED ZTP SCRIPT ######'
def monitoring_log(cmd, check_time): # 로그를 모니터링해서 수행할 동작을 정의한 함수 global stop_ethanalyzer while True: log_list = check_log(check_word) if len(log_list) > 0: stop_ethanalyzer = True # EthanalyzerThread의 동작을 중지시킵니다. print "로그가 발견되어 2차 실행 되는 ethanalyzer 입니다." cmd = remake_cmd_pcap_name(cmd, False) print "=" * 80, "\n", cmd cli(cmd) # 저장되는 이름에 after를 붙여서 저장 log = log_list[len(log_list) - 1] write_syslog(check_word, log) break time.sleep(check_time)
def add_banner(): banner_name = raw_input('Enter banner message:') result = validate_banner(banner_name) try: if result: cli.cli('configure terminal ; banner motd' + ' ' + banner_name) logger.info('banner added successfully') else: banner_name = banner_name[0:] + banner_name[0] cli.cli('configure terminal ; banner motd' + ' ' + banner_name) logger.info('banner added successfully') except BaseException: logger.error('Something went wrong while adding banner message') sys.exit(0)
def main(): import os # Python module names vary depending on nxos version try: from cli import cli except: from cisco import cli tmp_config_path = "volatile:poap.cfg" tmp_config_path_unix = "/volatile/poap.cfg" try: os.remove(tmp_config_path_unix) except: pass cli("copy <%=startupConfigUri%> %s vrf management" % tmp_config_path) cli("copy %s running-config" % tmp_config_path) cli("copy running-config startup-config") # copying to scheduled-config is necessary for POAP to exit on the next # reboot and apply the configuration. We want to merge the running-config # so we can work well with any other scripts that may also be applying # their changes to scheduled-config cli("copy running-config scheduled-config")
def lldpneigh(): u"""Getting LLDP neighbours information""" cmd = 'show lldp neighbors detail' infolist = ['System Description', 'Port Description', 'Management Address:', 'Local Port', 'System Name'] g = lambda x,y: cli.cli (cmd + ' | egrep \\"' + x + '\\"' + ' | awk \\"{print $' + str(y) + '}\\"' ) tuple1 = [] for idx, val in enumerate (infolist): if idx == 0: list1 = (cli.cli (cmd + ' | egrep \\"' + val + '\\"' + ' | sed \\"s/' + val + '//g\\"')).split('\n') tuple1.append(list1) #print list1 elif idx == 1: list2 = g(val,3).split('\n') tuple1.append(list2) elif idx ==2 : list3 = g(val,3).split('\n') tuple1.append(list3) elif idx == 3: list4 = g(val,4).split('\n') tuple1.append(list4) elif idx == 4: list5 = g(val,3).split('\n') tuple1.append(list5) patern = re.compile('xen|kvm|esx|ubuntu|vmware', re.IGNORECASE) i = 0 while i < (len(list1) - 1): if (re.search(patern, list1[i]) != None): if (re.search('xen', list1[i], re.IGNORECASE) != None): vminfo = 'xen' elif (re.search('esx', list1[i], re.IGNORECASE) != None): vminfo = 'esx' hyperv_patern = list1[i].split(': ')[0] + list1[i].split(': ')[1].split(' ')[0] hyperv = re.sub(u'[^A-Za-z\s]*', u'', hyperv_patern) portid = list2[i] ipaddr = list3[i] interf = list4[i] if not arg['virtualmachines']: print ('{0:15} \t\t {1:10} {2:25} {3:10} {4:15}'.format (hyperv.ljust(15), portid.ljust(29) , ipaddr.ljust(34), 'LLDP'.ljust(27), interf)) else: getvm(list5[i], vminfo, hyperv, portid) vminfo ='' i=i+1
def blue_beacon(sw_nums): """ Turns on blue beacon of given switch number list, if supported """ for num in sw_nums: # up to and including 16.8.x try: cli.cli('configure terminal ; hw-module beacon on switch %d' % num) except (cli.errors.cli_syntax_error, cli.errors.cli_exec_error): pass # from 16.9.x onwards try: cli.execute('hw-module beacon slot %d on' % num) except cli.CLISyntaxError: pass log(6, 'Switch %d beacon LED turned on' % num)
def get_platform(): # xml formatted output for show inventory inventory = cli('show inventory | format') # skip leading newline doc = minidom.parseString(inventory[1:]) PLATFORM = [] for node in doc.getElementsByTagName('InventoryEntry'): # What if there are several devices? chassis = node.getElementsByTagName('ChassisName')[0] # This match should catch most routers - ISR, ASR, CSR1000V if "Chassis" in chassis.firstChild.data: PLATFORM.append( node.getElementsByTagName('PID')[0].firstChild.data) # This match will catch anything Catalyst 9500 Series elif "c95xx Stack" in chassis.firstChild.data: PLATFORM.append( node.getElementsByTagName('PID')[0].firstChild.data) # This match will catch anything Catalyst 9300 Series elif "c93xx Stack" in chassis.firstChild.data: PLATFORM.append( node.getElementsByTagName('PID')[0].firstChild.data) # This match will catch anything Catalyst 3800 Series elif "c38xx Stack" in chassis.firstChild.data: PLATFORM.append( node.getElementsByTagName('PID')[0].firstChild.data) return PLATFORM
def deploy_startup_config(): startup_config_uri = '<%= (hasOwnProperty("startupConfigUri") ? startupConfigUri : "" )%>' if not startup_config_uri: return try: poap_log("Removing {0}".format(tmp_config_path_unix)) os.remove(tmp_config_path_unix) except: poap_log("Removing {0} failed".format(tmp_config_path_unix)) poap_log("Copying {0} to {1}".format(startup_config_uri, tmp_config_path)) cli("copy %s %s vrf management" % (startup_config_uri, tmp_config_path)) poap_log("Copying {0} to running-config".format(tmp_config_path)) cli("copy %s running-config" % tmp_config_path) poap_log("deploy_startup_config finished")
def main(): """ Main method. Parameters: None Returns: None """ # configure logging logger.configure() # cli arguments args = cli.cli() # parse origin if isinstance(args.origin, Point): origin = args.origin else: origin = Point.from_string(args.origin) # parse neighbors neighbors = parse_neighbors(args.neighbors) # determine nearest nearest_neighbors = nearest(origin, args.number, neighbors) # log summary summary(origin, nearest_neighbors) return
def check_stack(): text = cli.cli("show running-config | grep 'nxapi use-vrf'") if text: return True else: return False
def cdpneigh(): u"""Getting CDP neighbours information """ cmd = 'show cdp neighbor' cdp_dict = {} cdp = json.loads(cli.clid(cmd))['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] patern = re.compile('xen|kvm|esx|ubuntu|vmware', re.IGNORECASE) for row in cdp: if (re.search(patern, str(row)) != None): int_id = row['intf_id'] if int_id not in cdp_dict: cdp_dict[int_id] = {} cdp_dict[int_id]['intf_id'] = int_id cdp_dict[int_id]['platform_id'] = row['platform_id'] cdp_dict[int_id]['port_id'] = row['port_id'] try: for key, value in cdp_dict.items(): if 'port_id' in value and 'device_id' in value and 'intf_id' in value: continue except AttributeError: print ('There are not such attributes') finally: for key, value in cdp_dict.items(): neighbour = cli.cli('show cdp neighbors interface ' + value['intf_id'] + ' detail') ip = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', neighbour)[0] ipadd = str(ip) print ('{0:15} \t\t {1:10} {2:25} {3:10} {4:15}'.format (value['platform_id'].ljust(15), value['port_id'].ljust(29) , str(ip).ljust(34), 'CDP'.ljust(27), value['intf_id']))
def main(): import json # Python module names vary depending on nxos version try: from cli import cli except: from cisco import cli data = {} try: data['startup-config'] = cli('show startup-config')[0] data['running-config'] = cli('show running-config')[0] except: pass return data
def get_logs(): command_list_file = '/flash/command_list' logfile_raw = '/flash/logfile_' + datetime.now().strftime( '%Y-%m-%d-%H%M%S') logfile_name = logfile_raw + "tar.gz" try: fd = open(command_list_file, "r") except OSError as e: print(e) else: result = fd.read() fd.close() try: fd = open(logfile_raw, 'w') except OSError as e: print(e) else: for line in result.split('\n'): msg = '### ' + datetime.now().strftime( '%Y/%m/%d %H:%M:%S') + ' - ' + line + ' ###' fd.write(msg) fd.write(cli.cli(line)) fd.close() cmd = 'tar zcvf ' + logfile_name + " " + logfile_raw os.system(cmd) cmd = "rm -f " + logfile_raw os.system(cmd) return (logfile_name)
def cdpneigh(): u"""Getting CDP neighbours information """ cmd = 'show cdp neighbor' cdp_dict = {} cdp = json.loads(cli.clid( cmd))['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] patern = re.compile('xen|kvm|esx|ubuntu|vmware', re.IGNORECASE) for row in cdp: if (re.search(patern, str(row)) != None): int_id = row['intf_id'] if int_id not in cdp_dict: cdp_dict[int_id] = {} cdp_dict[int_id]['intf_id'] = int_id cdp_dict[int_id]['platform_id'] = row['platform_id'] cdp_dict[int_id]['port_id'] = row['port_id'] try: for key, value in cdp_dict.items(): if 'port_id' in value and 'device_id' in value and 'intf_id' in value: continue except AttributeError: print('There are not such attributes') finally: for key, value in cdp_dict.items(): neighbour = cli.cli('show cdp neighbors interface ' + value['intf_id'] + ' detail') ip = re.findall( r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', neighbour)[0] ipadd = str(ip) print('{0:15} \t\t {1:10} {2:25} {3:10} {4:15}'.format( value['platform_id'].ljust(15), value['port_id'].ljust(29), str(ip).ljust(34), 'CDP'.ljust(27), value['intf_id']))
def get_acl_ip(): ''' returns a list of IPS found in ACL :return: ''' acl = cli("show ip access-list %s" % ACLNAME).split('\n') p = re.compile('[\d]+\.[\d\.]+') return p.findall(''.join(acl))
def check_nxapi_enabled(): line = cli.cli("show feature | inc nxapi") if "disabled" in line: return False else: return True
def find_certs(): certs = cli('show run | include crypto pki') if certs: certs_split = certs.splitlines() certs_split.remove('') for cert in certs_split: command = 'no %s' % (cert) configure(command)
def validate_platform(): try: if 'N3K' in cli.cli('sh module'): return True else: return False except BaseException: logger.error('Caught exception whle validting switch platform') sys.exit(0)
def bulshit(vmhost, vminfo): cmdip = 'ping '+ vmhost + ' count 1 ' cmdiprun = cli.cli(cmdip) ipa = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', cmdiprun)[0] #ipfunc = lambda x: cli.cli ('ping '+ vmhost + ' count 1 ' ) cmdfunc = lambda x: cli.cli('run bash ssh root@' + ipa + ' ' + x ) if vminfo == 'xen': get_uuid_cmd = 'xe vm-list power-state=running params=uuid | egrep -o "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"' #cmd = 'run bash ssh root@' get_uuid_cmd uuid = cmdfunc(get_uuid_cmd).split('\n') #print uuid get_vm_name = 'xe vm-list params=name-label | awk "{print $5}" ' vm_names = cmdfunc(get_vm_name).split('\n\n') print vm_names ## распарсить строку elif vminfo == 'esx': print "Ebawulovo"
def update_desc_with_cdp_neighbors( neighbors): neigh_count = int(neighbors['neigh_count']) if neigh_count >1 : devices = neighbors['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] else: devices = [ neighbors['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] ] for device in devices: desc = get_user_desc(device['intf_id']) + " : to %(port_id)s of %(device_id)s" %device r = cli.cli('conf t ; interface %s ; desc %s' %(device['intf_id'], desc)) print r
def deploy_boot_images(): poap_log("deploy_boot_images") boot_image_uri = '<%= (hasOwnProperty("bootImageUri") ? bootImageUri : "" )%>' if not boot_image_uri: poap_log("No boot image URL: {0}".format("<%=bootImageUri%>")) return poap_log("boot image URL {0}".format("<%=bootImageUri%>")) image_dir = "bootflash:poap_images" image_dir_new = "%s_new" % image_dir image_dir_unix = "/bootflash/poap_images" image_dir_new_unix = "%s_new" % image_dir_unix image_dir_old_unix = "%s_old" % image_dir_unix # Cisco won't let us remove images being used for the current boot, # so mark them for deletion on the NEXT upgrade. This means we will have # three image versions on disk: # - The current ones (bootflash:poap_images_new/) # - The previous ones (bootflash:poap_images_old/) # - The original ones which we never modify (bootfalsh:) if os.path.isdir(image_dir_old_unix): shutil.rmtree(image_dir_old_unix) if os.path.isdir(image_dir_new_unix): os.rename(image_dir_new_unix, image_dir_old_unix) else: os.mkdir(image_dir_old_unix) os.mkdir(image_dir_new_unix) # Download images poap_log("Downloading images") image_path = "%s/<%=bootImage%>" % image_dir_new poap_log("From: %s to %s" % (boot_image_uri, image_path)) cli("copy %s %s vrf management" % (boot_image_uri, image_path)) # Set boot variables, system image first cli("configure terminal ; boot nxos %s" % image_path)
def main(): try: deploy_startup_config() deploy_boot_images() except Exception as e: poap_log("Deploy startup or boot failed") poap_log_close() # Don't swallow exceptions otherwise the Cisco switch will think the POAP was a success # and proceed to boot rather than retrying raise e # Copying to scheduled-config is necessary for POAP to exit on the next # reboot and apply the configuration. We want to merge the running-config # changes made by both the startup-config deployment # and the boot image deployment. # The issue is if we copy to scheduled-config MORE THAN ONCE it will # trigger POAP/config application MORE THAN ONCE as well, which we don't want. # So we have to do all these operations in the same script, that way they # are not order-dependant. poap_log("Deploying images") poap_log("From: %s to %s" % ("running-config", "startup-config")) cli("copy running-config startup-config") poap_log("From: %s to %s" % ("running-config", tmp_config_path)) cli("copy running-config %s" % tmp_config_path) poap_log("From: %s to %s" % (tmp_config_path, "scheduled-config")) cli("copy %s scheduled-config" % tmp_config_path) poap_log_close()
def startAWS(self, server): clustername = server.cluster_name master_name = cli.cli( ['listmaster', clustername] ) if master_name: self.messagelogger.write("OK: Found an existing AWS cluster with master %s!\n" %(master_name)) else: self.messagelogger.write("WARNING: No AWS cluster is running currently!\n") try: start_cluster = cli.cli( ['start', clustername, '-c', server.amazon_aws_config ] ) except: start_cluster = cli.cli( ['terminate', clustername ] ) start_cluster = cli.cli( ['start', clustername, '-c', server.amazon_aws_config ] ) master_name = cli.cli( ['listmaster', clustername] ) if master_name: self.messagelogger.write("SUCCESS: Successfully created a cluster with master %s!\n" %(master_name)) else: self.messagelogger.write("FAILED: Failed to create a cluster!\n") return None # return master_name
def update_desc_with_cdp_neighbors_nexus72( neighbors): mydevices = {} for item in neighbors.keys(): keys = item.split('/') if keys[1] in ['intf_id', 'port_id', 'device_id'] : if not mydevices.has_key( keys[2]): dev = {} dev[ keys[1]] = neighbors[item] mydevices[ keys[2]] = dev for idx in mydevices.keys(): desc = "to %(port_id)s of %(device_id)s" %mydevices[idx] r = cli.cli('conf t ; interface %s ; desc %s' %(mydevices[idx]['intf_id'], desc)) print r
def get_all_port_channels_and_members(self): """ Get all the membership information from software. Return a dictionary keyed by PO ifindex, containing a list of members' ifindices """ # Get the port-channel summary data, but skip the header data = cli.cli("show port-channel summary").split("\n")[11:] membership = {} i = 0 po_key = "" while i < len(data): overflow = False # Split everything on space, but skip the empty strings line = filter(lambda x: x, re.split("\s+", data[i])) members = [] for j in range(len(line)): # Skip the type and protocol entries # If the members have overflowed to the next line # don't skip them if not overflow and j in [2,3]: continue match = re.search("Eth(\d+/\d+\/?\d*)\s*\(([A-z])\)", line[j]) if match: # Only get the up ports if match.group(2) in ["P", "p"]: (ret, ifidx) = py_im_get_if_index_from_name("Ethernet%s" % match.group(1)) members.append(ifidx) # If there's a member as the first item on a line, # then we've overflowed a single line; act accordingly if j == 0: overflow = True else: # Only match up port-channels match = re.search("Po(\d+)\([A-Z]U\)", line[j]) if match: # We've hit a port-channel entry, reset overflow (ret, ifidx) = py_im_get_if_index_from_name("Port-channel%s" % match.group(1)) po_key = ifidx overflow = False # only throw away the key if we aren't overflowing a single line elif not overflow: po_key = "" # Create the mapping. No need to sort since members are already sorted if po_key != "": membership[po_key] = membership.get(po_key, []) + members i += 1 return membership
def __init__(self): self.menu_targets = ( ('jace', 'Jupiter Ace', util.cr, self.target_jace, None), ('tec1', 'Talking Electronics TEC-1', util.cr, self.target_tec1, None), ) self.menu_root = ( ('exit', 'exit the application', util.cr, self.exit, None), ('help', 'display general help', util.cr, self.general_help, None), ('target', 'select a target', None, None, self.menu_targets), ('version', 'display version information', util.cr, self.version, None), ) # create the cli self.io = conio.console() self.cli = cli.cli(self) self.main_menu()
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 main(): try: while True: operation = raw_input("Do you want to shut/unshut all interfaces [shut(S)/unshut(U)/no_action(N)] - ") if operation in ['S','U']: interfaces = cli.cli('sh run int | no-more') interface_response = interface_parser(interfaces) interface_names = '' if len(interface_response['port-channel']) != 0: interface_names = ','.join(interface_response['port-channel']) if operation == 'S': cli.cli('configure terminal ; interface '+ interface_names + ' ; shutdown ; end') logger.info("Successfully shutted down the port-channel interfaces") elif operation == 'U': cli.cli('configure terminal ; interface '+ interface_names + ' ; no shutdown ; end') logger.info("Successfully unshutted the port-channel interfaces") if len(interface_response['Ethernet']) != 0: interface_names = ','.join(interface_response['Ethernet']) if operation == 'S': cli.cli('configure terminal ; interface '+ interface_names + ' ; shutdown ; end') logger.info("Successfully shutted down the ethernet interfaces") elif operation == 'U': cli.cli('configure terminal ; interface '+ interface_names + ' ; no shutdown ; end') logger.info("Successfully unshutted the ethernet interfaces") break elif operation == 'N': break else: print "Invalid input" except BaseException: logger.error( 'Something went wrong while fetching switch platform and nxos') sys.exit(0) install()
def main(): deploy_startup_config() deploy_boot_images() # Copying to scheduled-config is necessary for POAP to exit on the next # reboot and apply the configuration. We want to merge the running-config # changes made by both the startup-config deployment # and the boot image deployment. # The issue is if we copy to scheduled-config MORE THAN ONCE it will # trigger POAP/config application MORE THAN ONCE as well, which we don't want. # So we have to do all these operations in the same script, that way they # are not order-dependant. cli("copy running-config startup-config") cli("copy running-config %s" % tmp_config_path) cli("copy %s scheduled-config" % tmp_config_path)
def add_span(): try: cli.cli('configure terminal ; spanning-tree mode mst') logger.info('spanning-tree mode mst' + ' command executed successfully') cli.cli('configure terminal ; vlan configuration 1-3967') logger.info('vlan configuration 1-3967' + ' command configured successfully') cli.cli( 'configure terminal ; no spanning-tree vlan 1-3967') logger.info( 'no spanning-tree vlan 1-3967' + ' command configured successfully') except BaseException: logger.error('Something went wrong while' + 'executing spanning tree and vlan configuration') sys.exit(0)
cur_thresh = thresh_item[key] prev_thresh = prev_thresh_item[key] need_update = False if (float(prev_thresh) <= 0): if float(prev_thresh) != float(cur_thresh): need_update = True else: need_update = abs( float(cur_thresh) - float(prev_thresh) ) * 100 / float(prev_thresh) > 25 if need_update: thresh_dif.setdefault(iface_name, {}) thresh_dif[iface_name][key] = {"prev" : float(prev_thresh), "new" : float(cur_thresh)} break if thresh_dif: data["THRESHOLDDIFF"] = thresh_dif logs = cli.cli("show logging").split('\n') logs_variables = {} for line in logs: if line.find("TRACEBACK") != -1: logs_variables.setdefault("TRACEBACK", []).append(line) elif line.find("authentication failed") != -1: logs_variables.setdefault("AUTHFAIL", []).append(line) elif line.find("neighbor down") != -1: logs_variables.setdefault("NEIDOWN", []).append(line) if logs_variables: data["LOGS"] = logs_variables with open(new_logfile, 'w+') as outfile: json.dump(data, outfile)
def get_show_run_all_output(): output = cli.cli("show run all") with open("/tmp/cli_dump.cmd", "w") as text_file: text_file.write(output)
else: NXAPITransport.cli(cmd) cli = smartcli clid = NXAPITransport.clid cdp_dict = {} cdp = json.loads(clid('show cdp neighbor')) cdp = findkey(cdp, 'ROW_cdp_neighbor_brief_info')[0] for entry in cdp: intf_id = entry['intf_id'] if intf_id not in cdp_dict: cdp_dict[intf_id] = { 'intf_id': intf_id, 'device_id': entry['device_id'], 'port_id': entry['port_id'] } for key, value in cdp_dict.items(): if 'port_id' in value and 'device_id' in value and 'intf_id' in value: fields = { 'interface': value['intf_id'].strip().encode('UTF-8'), 'device_id': value['device_id'].strip().encode('UTF-8'), 'port_id': value['port_id'].strip().encode('UTF-8') } cmd = 'conf t ; interface {interface} ; description {device_id} {port_id}'.format( **fields) print(cmd) cli(cmd)