def show_run(switch_ip, intf_id): ''' This accepts the switch info and and interface. params: switch_ip (string): ip address of switch intf_id (string): interface to check config ''' switch_user = '******' switch_pw = 'cisco123' # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse VLAN data into dictionary command = switch.show('show interface ' + intf_id + ' switchport') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface'] oper_mode = results['oper_mode'] access_vlan = results['access_vlan'] # Parse description data into dictionary command = switch.show('show interface ' + intf_id) show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface'] if 'desc' in results: desc = 'description ' + results['desc'] else: desc = "no description" # Create NXOS formatted text to return config_text = 'interface ' + intf_id + '\n ' + desc + '\n switchport mode ' + oper_mode + \ '\n switchport access vlan ' + access_vlan + '\n!\n' return config_text
def show_run(switch_ip, intf_id): switch_user = '******' switch_pw = 'cisco123' switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() command = switch.show('show interface ' + intf_id + ' switchport') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface'] oper_mode = results['oper_mode'] access_vlan = results['access_vlan'] command = switch.show('show interface ' + intf_id) show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface'] desc = results['desc'] config_text = 'interface ' + intf_id + '\n description ' + desc + '\n switchport mode ' + oper_mode + '\n switchport access vlan ' + access_vlan + '\n!\n' return config_text
class Monitor(QFrame): def __init__(self, ip, parent=None): super().__init__(parent) self.ip = ip self.socket_ = QUdpSocket() self.detail_device = None self.verticalLayout = QVBoxLayout() self.label = QLabel(parent) self.label.setMinimumSize(QSize(300, 200)) self.label.setMaximumSize(QSize(300, 200)) self.label.setScaledContents(True) self.verticalLayout.addWidget(self.label) self.monitor = QPushButton(parent) self.monitor.setMinimumSize(QSize(300, 20)) self.monitor.setMaximumSize(QSize(300, 20)) self.verticalLayout.addWidget(self.monitor) self.hide_item() self.set_connect() def hide_item(self): self.monitor.hide() def show_item(self, mac, port): self.monitor.setText(mac) self.monitor.show() self.label.show() self.socket_.bind(QHostAddress(self.ip), port) self.socket_.readyRead.connect(self.show_video) self.detail_device = Device(monitor=self) def show_video(self): data = self.socket_.readDatagram(65535)[0] data = zlib.decompress(data) video_show = QPixmap() video_show.loadFromData(data) self.label.setPixmap(video_show) self.detail_device.video_monitor.setPixmap(video_show) def get_current_image(self): return self.label.pixmap() def set_connect(self): self.monitor.clicked.connect(self.show_detail) def show_detail(self): self.detail_device.show()
def create_file(ip_address,command,filename): sw1 = Device(ip = ip_address, username = '******', password = '******') sw1.open() command1 = sw1.show(command) try: os.remove(filename) except: pass file1 = open(filename,'w') file1.write(command1[1]) file1.close()
def show_run(switch_ip, intf_id): """ This accepts the switch info and and interface. params: switch_ip (string): ip address of switch intf_id (string): interface to check config """ switch_user = "******" switch_pw = "cisco123" # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse VLAN data into dictionary command = switch.show("show interface " + intf_id + " switchport") show_dict = xmltodict.parse(command[1]) results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"] oper_mode = results["oper_mode"] access_vlan = results["access_vlan"] # Parse description data into dictionary command = switch.show("show interface " + intf_id) show_dict = xmltodict.parse(command[1]) results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"] if "desc" in results: desc = "description " + results["desc"] else: desc = "no description" # Create NXOS formatted text to return config_text = ( "interface " + intf_id + "\n " + desc + "\n switchport mode " + oper_mode + "\n switchport access vlan " + access_vlan + "\n!\n" ) return config_text
def getswitchinfo(sw): switch = Device(ip=sw) switch.open() getdata = switch.show('show interface brief') show_intf_dict = xmltodict.parse(getdata[1]) data = show_intf_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface'] #rint data # Code to loop through interfaces and put all 'up' in a list (align list with key) up_list= [] for each in data: if 'up' in each.values(): up_list.append(each['interface']) #print up_list return up_list
def get_intfs(switch_ip): ''' This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. ''' switch_user = '******' switch_pw = 'cisco123' switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() command = switch.show('show interface') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface'] intf_list = [] for result in results: if 'eth_mode' in result and result['eth_mode'] == 'access': intf_list.append(result['interface']) return intf_list
def get_intfs(switch_ip): """ This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. """ switch_user = "******" switch_pw = "cisco123" switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() command = switch.show("show interface") show_dict = xmltodict.parse(command[1]) results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"] intf_list = [] for result in results: if "eth_mode" in result and result["eth_mode"] == "access": intf_list.append(result["interface"]) return intf_list
def getswitchinfo(sw): switch = Device(ip=sw) switch.open() getdata = switch.show('show interface brief') show_intf_dict = xmltodict.parse(getdata[1]) data = show_intf_dict['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface'] #rint data # Code to loop through interfaces and put all 'up' in a list (align list with key) up_list = [] for each in data: if 'up' in each.values(): up_list.append(each['interface']) #print up_list return up_list
def get_intfs(switch_ip): """ This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. """ switch_user = '******' switch_pw = 'cisco123' switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() command = switch.show('show interface') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface'] intf_list = [] for result in results: if 'eth_mode' in result and result['eth_mode'] == 'access': intf_list.append(result['interface']) return intf_list
def get_vlans(switch_ip): ''' This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. ''' switch_user = '******' switch_pw = 'cisco123' switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() command = switch.show('show vlan') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body']['TABLE_vlanbrief']['ROW_vlanbrief'] vlan_list = [] for result in results: if 'USER' in result['vlanshowbr-vlanname']: vlan_list.append([result['vlanshowbr-vlanid-utf'], result['vlanshowbr-vlanname']]) # print json.dumps(show_dict, indent=4) return vlan_list
def get_switch(crawler, f): '''Open the switch, grab the hostname, and run show_lldp_neigh''' try: switch = Device(ip=crawler.current_address, username=crawler.username, password=crawler.password) switch.open() print crawler.current_address xmlHostname = switch.show('show hostname') dictHostname = xmltodict.parse(xmlHostname[1]) crawler.update_hostname(dictHostname['ins_api']['outputs']['output']['body']['hostname']) show_lldp_neigh(switch, crawler, f) return False except Exception, e: print "Could not connect using NXAPI, trying a screenscrape..." error_flag = screen_scrape(crawler, f) return error_flag
def get_vlans(switch_ip): """ This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. """ switch_user = "******" switch_pw = "cisco123" # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse data into dictionary command = switch.show("show vlan") show_dict = xmltodict.parse(command[1]) results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_vlanbrief"]["ROW_vlanbrief"] vlan_list = [] for result in results: if "USER" in result["vlanshowbr-vlanname"]: vlan_list.append([result["vlanshowbr-vlanid-utf"], result["vlanshowbr-vlanname"]]) # print json.dumps(show_dict, indent=4) return vlan_list
def show_cdp_nei2(sw): #this function logins to the switch and display the CDP neighbor details try: switch2 = Device(ip=sw, username='******', password='******') switch2.open() getdata2 = switch2.show('show cdp nei detail') show_intf_dict2 = xmltodict.parse(getdata2[1]) data2 = show_intf_dict2['ins_api']['outputs']['output']['body']['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info'] print "*****************************************************************************************************************" print "CDP Neighbors of Next Switch: " + sw print "===================================" iplist5=[] j= len(data2) i=0 for key,value in data2[i].iteritems(): if i == j: continue else: print "Device : " + data2[i]['device_id'] print "Mgmt IP : " + data2[i]['v4mgmtaddr'] print "Platform: " + data2[i]['platform_id'] print "Local If: " + data2[i]['intf_id'] print "RemoteIF: " + data2[i]['port_id'] print "===================================" iplist5.append(data2[i]['v4mgmtaddr']) #print iplist5[i] i=i+1 k=len(iplist5) print ("Number of neighbors of next switch: " , k) print "Neighbors of next switch: " print iplist5 #The following command appends the successful list with the switch IP address swsuccess.append(sw) return iplist5 except: #The following code is used in case the function is not able to login to the switch. print ("Unable to login to :" , sw) #The following code appends the failure list with the ip address of the switch. swfail.append(sw) iplist6=[] return iplist6
def show_version(): ''' :return: returns the version from the json return from a switch using provided nxapi modules. ''' args = getargs() username = args.user if not username: username = raw_input("Username: "******"Password: ") sw1 = Device(ip=args.ip, username=username, password=password) sw1.open() getversion = sw1.show('show version') result = xmltodict.parse(getversion[1]) data = result['ins_api']['outputs']['output']['body']['kickstart_ver_str'] return data
def get_vlans(switch_ip): ''' This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. ''' switch_user = '******' switch_pw = 'cisco123' # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse data into dictionary command = switch.show('show vlan') show_dict = xmltodict.parse(command[1]) results = show_dict['ins_api']['outputs']['output']['body'][ 'TABLE_vlanbrief']['ROW_vlanbrief'] vlan_list = [] for result in results: if 'USER' in result['vlanshowbr-vlanname']: vlan_list.append([ result['vlanshowbr-vlanid-utf'], result['vlanshowbr-vlanname'] ]) # print json.dumps(show_dict, indent=4) return vlan_list
for number in threes: print(number) from dice import sum_of_dice print('########## DICE ###########') threeD8 = sum_of_dice(8, 3) print(f"You rolled {threeD8} on three 8-sided dice.") print('############ class instantiaion ############') from device import Device dev1 = Device('Router') dev2 = Device('Switch') print(f"Device 1 name: {dev1.hostname}, Message: {dev1.motd}") print(dev1.show('hostname')) print('########### using while with dictionary ##############') playerChoices = {} keepOn = True while keepOn: name = input("Enter your name ") classOfPC = input("Enter your class ") playerChoices[name] = classOfPC keepOn = (input("Keep Going? (enter y to go on) ") == 'y') print(playerChoices)
app_file_name = file_list[1] #Approved version check file must come first after verchk.py ip_file_name = file_list[2] #IP Address List file must come after approved version. file_object = open(app_file_name,"r") app_version = file_object.readline().strip() print "\nThis is the approved version: ",app_version,"\n\tSwitches not running this version will require an upgrade" ip_file_object = open(ip_file_name,"r") ip_addresses = ip_file_object.readline().strip() ip_address_list = ip_addresses.split(',') for each_ip in ip_address_list: switch = Device(ip=each_ip,username='******',password='******') switch.open() shver_command_out = switch.show('show version') result = xmltodict.parse(shver_command_out[1]) sw_version = result['ins_api']['outputs']['output']['body']['kickstart_ver_str'] sw_hostname = result['ins_api']['outputs']['output']['body']['host_name'] sw_chassis = result['ins_api']['outputs']['output']['body']['chassis_id'] sw_chassis_list = sw_chassis.split(' ') sw_model = sw_chassis_list[1] print "=" * 75 print "\n\tHostname:",sw_hostname,"\n\tIP Address:",each_ip print "\tSwitch Model: ",sw_model if sw_version == app_version: print "\tNo upgrade required"
from device import Device sw1 = Device(ip='172.31.217.138', username='******', password='******') sw1.open() command = sw1.show('show int e1/48') print command import xmltodict import json command = sw1.show('sh int e1/48') result = xmltodict.parse(command[1]) print json.dumps( result, indent=4) ip = result['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_addr'] print ip mask = result['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_mask'] print mask print ip + '/' + mask sh_vlan = sw1.show('sh vl') sh_vlan_dict = xmltodict.parse(sh_vlan[1]) print json.dumps( sh_vlan_dict, indent=4) vlan10_name = sh_vlan_dict['ins_api']['outputs']['output']['body']['TABLE_vlanbrief']['ROW_vlanbrief'][1]['vlanshowbr-vlanname']
def main(): """ This is the main body of the script. This script reads in a file containing IP addresses and using the NX-OS API pulls CDP information from each device (IP) and stores it in a CSV file named cdp-output.csv in the local directory. """ #Initialize the list data structure that will hold the IPs from the given file ip_list = [] #Initialize the list data structure that will hold the cdp information extracted from each switch. #This will be a list of lists. nei_list = [] #Store the path and filename provided as the first argument in the variable "ip_file_path" ip_file_path = sys.argv[1] #Using the file_accessible function, make sure that the file exists before trying to open it. ip_file_accessible = file_accessible(ip_file_path,'r') if ip_file_accessible: # If the function file_accessible returned 'True' then the file is good and can be processed. ip_fh = open(ip_file_path, 'r') # Open the file given as an argument which should contain one IP address per line ip_l = ip_fh.readlines() #Use the xxx.readlines() function to read in each line of the file into a list. # Using list comprehension populate the ip_list varialbe with valid IPs without leading or trailing CR,LF, or whitespace # within the list comprehension command call the qa_ipformat to ensure its a properly formatted IP string ip_list = [ip.strip() for ip in ip_l if len(ip)>0 and qa_ipformat(ip.strip())] #print "ip_list: ", ip_list #Troubleshooting print statement. Should be commented out of working code. else: # if the file_accessible function returned 'False' the file provided is not accessible and the script should end gracefully. #Function returned Fals so the file does not exist. Print error and exit out of script. print("The file <" + ip_file_path + "> cannot be found. Please verify path and file name and try again.") sys.exit() #The file given in the command line is not accessible so print a notification and exit out of the script. # Define credentials to use for devices un = 'admin' pw = 'cisco123' #Header line printed to stdout (screen) to inform the user of what the script is doing. print "\n" + "="*20 + "Processing Devices in file " + ip_file_path + "="*20 for dev_ip in ip_list: #This for loop interates through each element of the list ip_list #print "\nProcessing device with IP: ",ip # Using the imported function Device in module device define the parameters to establish a session with the device. dev = Device(ip=dev_ip,username=un,password=pw) # Open a session to the device dev.open() # Run the 'show version' command to get the hostname of the device # First get the output of the command sh_ver_cmd_out = dev.show('show version') host_name = get_hostname(sh_ver_cmd_out) print "hostname from main(): ",host_name # Run the 'show cdp neighbor' command on the device and store the resulting output in cdp_cmd. This will return a tuple of dictionaries. cdp_cmd = dev.show('show cdp neighbor') # Take the command output stored in the second tuple [1] and store it in xlm format in the cdp_out variable # The cdp_out variable now has the actual 'show cdp neighbor' data cdp_out = xmltodict.parse(cdp_cmd[1]) #print json.dumps(cdp_out, indent=3) #Troubleshooting print statement. Should be commented out of working code. # Using the json.dumps output to determine the structure of the cdp_out dictionary or the "path" that must be walked to get to the values needed # The cdp_nei_list is a list of dictionaries. Each element describes the neighbor information. cdp_nei_list = cdp_out['ins_api']['outputs']['output']['body']['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] #print "cdp_nei_list: ", cdp_nei_list #Troubleshooting print statement. Should be commented out of working code. #print "lenght of cdp_nei_list: ",str(len(cdp_nei_list)) #Troubleshooting print statement. Should be commented out of working code. # Interate through each element of the list which contains a dictionary describint each cdp neighbor entry. for nei in cdp_nei_list: #print nei #Print the IP of the current switch, the id of the neighbor, the local interface, the platform of the neighbor and the neighbor or remote interface print dev_ip,nei['device_id'],host_name, nei['intf_id'],nei['platform_id'],nei['port_id'] #record the values printed in a CSV format so each row describing a neighbor can be saved to a file at the end of processing nei_list.append(dev_ip + "," + host_name + "," + nei['device_id'] + "," + nei['intf_id'] + "," + nei['platform_id'] + "," + nei['port_id'] + "\n") #print nei_list #Troubleshooting print statement. Should be commented out of working code. #print len(nei_list) #Troubleshooting print statement. Should be commented out of working code. # Open a file that will be used to Write the neighbor results and name it 'cdp-output.csv' out_fh = open('cdp-output.csv','w') out_fh.write("Local IP, Local Hostname, Remote Hostname, Local Interface, Remote Model, Remote Interface \n") # Iterate through the nei_list list data structure and write a line to the output file for each element in the list representing a neighbor. for row in nei_list: # This command writes one "row" to the 'cdp-output.csv' file out_fh.write(row) # Close the cdp-output.csv file out_fh.close()
#/usr/bin/env python -tt import xmltodict import json from device import Device sw1 = Device(ip='172.31.217.138', username='******', password='******') sw1.open() cmd_sh_hardware = sw1.show('show hardware') result_hardware = xmltodict.parse(cmd_sh_hardware[1]) cmd_sh_intf_mgmt = sw1.show('sh int mgmt0') result_intf_mgmt = xmltodict.parse(cmd_sh_intf_mgmt[1]) hostname = result_hardware['ins_api']['outputs']['output']['body']['host_name'] os_version = result_hardware['ins_api']['outputs']['output']['body']['rr_sys_ver'] mgmt_intf_ip = result_intf_mgmt['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_addr'] mgmt_intf_mask = result_intf_mgmt['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_mask'] mgmt_intf_desc = result_intf_mgmt['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['desc'] mgmt_intf_speed = result_intf_mgmt['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_speed'] mgmt_intf_duplex = result_intf_mgmt['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_duplex'] device_make = result_hardware['ins_api']['outputs']['output']['body']['chassis_id'] device_rr = result_hardware['ins_api']['outputs']['output']['body']['rr_reason'] device_uptime_days = result_hardware['ins_api']['outputs']['output']['body']['kern_uptm_days'] device_uptime_hours = result_hardware['ins_api']['outputs']['output']['body']['kern_uptm_hrs'] device_uptime_min = result_hardware['ins_api']['outputs']['output']['body']['kern_uptm_mins'] device_uptime_sec = result_hardware['ins_api']['outputs']['output']['body']['kern_uptm_secs'] device_btflash = result_hardware['ins_api']['outputs']['output']['body']['bootflash_size'] device_sn = result_hardware['ins_api']['outputs']['output']['body']['TABLE_slot']['ROW_slot']['TABLE_slot_info']['ROW_slot_info']
# Nexus IP, Credentials, and Open NX-API Connection # n9k = Device(ip=n9k_ip, username=n9k_user, password=n9k_pass) n9k.open() # Open file(s) for collecting output data # f_intstat = open('intstat.dat', "w") f_swprts = open('swprts.dat', "w") f_ipprts = open('ipprts.dat', "w") f_hard = open('hardware.dat', "w") # Collect & print "show hardware output # sh_hardware = n9k.show('show hardware') hardware_dict = xmltodict.parse(sh_hardware[1]) hw_data = hardware_dict['ins_api']['outputs']['output']['body'] hw_data_output = json.dumps( hardware_dict, indent=4) hw_dict = {} hw_dict['os_version'] = hw_data['kickstart_ver_str'] hw_dict['type'] = hw_data['chassis_id'] hw_dict['memory'] = hw_data['memory'] + hw_data['mem_type'] hw_dict['hostname'] = hw_data['host_name'] hw_dict['bootflash'] = hw_data['bootflash_size'] hw_dict['last_reboot_reason'] = hw_data['rr_reason'] hw_dict['uptime'] = '{} day(s) {} hour(s) {} min(s) {} sec(s)'.format(hw_data['kern_uptm_days'],hw_data['kern_uptm_hrs'],hw_data['kern_uptm_mins'],hw_data['kern_uptm_secs']) ser_nums = {} ser_nums_data = hardware_dict['ins_api']['outputs']['output']['body']['TABLE_slot']['ROW_slot']['TABLE_slot_info']['ROW_slot_info'] for each in ser_nums_data: if 'serial_num' in each.keys():
#!/usr/bin/env python import xmltodict from device import Device if __name__ == "__main__": switch = Device(ip='192.168.200.50') switch.open() my_data = switch.show('show cdp neighbors') result = xmltodict.parse(my_data[1]) cdp_table = result['ins_api']['outputs']['output']['body'] \ ['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] for each_neighbor in cdp_table: print '=' * 40 for key, value in each_neighbor.iteritems(): if key == 'intf_id': print 'Local Interface: ', value if key == 'device_id': print 'Neighbor: ', value if key == 'port_id': print 'Neighbor Interface: ', value print '=' * 40
def main(): args = sys.argv if len(args) == 4: #This section will check to see if the file pass to Python in a argument actually exists if os.path.exists(args[1]): switch_ips = open(args[1]).read().splitlines() else: print 'File ', os.path.realpath(args[1]), 'does not exist. Please try again' sys.exit(1) #For look to open each switch in the list of IP addresses passed via CLI arguments for switch_ip in switch_ips: switch = Device(ip=switch_ip,username=args[2],password=args[3]) switch.open() #These lines gat the XML output from the XML API on the N9K getswitchhardwaredata = switch.show('show hardware') getswitchvpcdata = switch.show('show vpc') getvpccondata = switch.show('show vpc consistency-parameters global') #These lines parse the XML into JSON format getswitchvpcdatajson = xmltodict.parse(getswitchvpcdata[1]) getswitchhardwaredatajson = xmltodict.parse(getswitchhardwaredata[1]) getvpccondatajson = xmltodict.parse(getvpccondata[1]) #This grabs the name on the switch switchname = get_hostname(getswitchhardwaredatajson) #<<<This is the start of outputting information regarding a switch>>> print '=' * 20, switchname, '=' * 20 #This sends the show vpc command and show vpc con global command JSON data to the function to check for problems. #This will also return a list of the indivdual vPCs that are configured on the switch. vpcinfo = vpc_check(getswitchvpcdatajson,getvpccondatajson) #Calls a function to return the vPC IDs from the switch. vpc_list = list_vpc_nums(vpcinfo) #Now we take the list of vPC IDs and call the NXAPI with the command show vpc con vpc X vpc_error_count = 0 for each in vpc_list: stringeach = str(each) string_cmd = 'show vpc consistency-parameters vpc ' string_cmd += stringeach #This line takes the string_cmd variable and uses that to run the commmand with the customer VPC ID getvpccondetail = switch.show(string_cmd) #Parse the XML to JSON getvpccondetailjson = xmltodict.parse(getvpccondetail[1]) #This calls a function to check each indivdual vPC for inconsistencies is_vpc_error = vpc_con_check(each,getvpccondetailjson) if is_vpc_error == True: vpc_error_count +=1 #This section will monitor if any vPCs returned mismatches, if none did, then it prints there were no errors. if is_vpc_error == False:# if vpc_error_count == 0: print '===No vPC consistency issues===\n' #<<<This is the end of outputting information regarding a switch>>> print '=' * 20, switchname, '=' * 20 , '\n' else: print 'ERROR: Invalid syntax\n'\ 'Example: \"python vPCconcheck.py file.txt username password\"' sys.exit(1)
for each_ip in ip_address_list: #check to see it the IP address passed is a valid host cmd = shlex.split("ping -n 1 ") cmd.append(each_ip) #print "cmd: ",cmd try: output = subprocess.check_output(cmd) except subprocess.CalledProcessError, e: print each_ip, " is not valid" continue else: switch = Device(ip=each_ip, username='******', password='******') switch.open() shver_command_out = switch.show('show version') result = xmltodict.parse(shver_command_out[1]) #print json.dumps(result, indent=4) sw_version = result['ins_api']['outputs']['output']['body'][ 'kickstart_ver_str'] sw_hostname = result['ins_api']['outputs']['output']['body'][ 'host_name'] sw_chassis = result['ins_api']['outputs']['output']['body'][ 'chassis_id'] sw_chassis_list = sw_chassis.split(' ') sw_model = sw_chassis_list[1] print "=" * 75
from device import Device sw1 = Device(ip='172.31.217.138', username='******', password='******') sw1.open() command = sw1.show('show int e1/48') print command import xmltodict import json command = sw1.show('sh int e1/48') result = xmltodict.parse(command[1]) print json.dumps(result, indent=4) ip = result['ins_api']['outputs']['output']['body']['TABLE_interface'][ 'ROW_interface']['eth_ip_addr'] print ip mask = result['ins_api']['outputs']['output']['body']['TABLE_interface'][ 'ROW_interface']['eth_ip_mask'] print mask print ip + '/' + mask sh_vlan = sw1.show('sh vl') sh_vlan_dict = xmltodict.parse(sh_vlan[1]) print json.dumps(sh_vlan_dict, indent=4) vlan10_name = sh_vlan_dict['ins_api']['outputs']['output']['body'][ 'TABLE_vlanbrief']['ROW_vlanbrief'][1]['vlanshowbr-vlanname']
# Nexus IP, Credentials, and Open NX-API Connection # n9k = Device(ip=n9k_ip, username=n9k_user, password=n9k_pass) n9k.open() # Open file(s) for collecting output data # f_intstat = open('intstat.dat', "w") f_swprts = open('swprts.dat', "w") f_ipprts = open('ipprts.dat', "w") f_hard = open('hardware.dat', "w") # Collect & print "show hardware output # sh_hardware = n9k.show('show hardware') hardware_dict = xmltodict.parse(sh_hardware[1]) hw_data = hardware_dict['ins_api']['outputs']['output']['body'] hw_data_output = json.dumps(hardware_dict, indent=4) hw_dict = {} hw_dict['os_version'] = hw_data['kickstart_ver_str'] hw_dict['type'] = hw_data['chassis_id'] hw_dict['memory'] = hw_data['memory'] + hw_data['mem_type'] hw_dict['hostname'] = hw_data['host_name'] hw_dict['bootflash'] = hw_data['bootflash_size'] hw_dict['last_reboot_reason'] = hw_data['rr_reason'] hw_dict['uptime'] = '{} day(s) {} hour(s) {} min(s) {} sec(s)'.format( hw_data['kern_uptm_days'], hw_data['kern_uptm_hrs'], hw_data['kern_uptm_mins'], hw_data['kern_uptm_secs']) ser_nums = {} ser_nums_data = hardware_dict['ins_api']['outputs']['output']['body'][
#/usr/bin/env python -tt import xmltodict import json from device import Device sw1 = Device(ip='172.31.217.138', username='******', password='******') sw1.open() cmd_sh_hardware = sw1.show('show hardware') result_hardware = xmltodict.parse(cmd_sh_hardware[1]) cmd_sh_intf_mgmt = sw1.show('sh int mgmt0') result_intf_mgmt = xmltodict.parse(cmd_sh_intf_mgmt[1]) hostname = result_hardware['ins_api']['outputs']['output']['body']['host_name'] os_version = result_hardware['ins_api']['outputs']['output']['body'][ 'rr_sys_ver'] mgmt_intf_ip = result_intf_mgmt['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface']['eth_ip_addr'] mgmt_intf_mask = result_intf_mgmt['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface']['eth_ip_mask'] mgmt_intf_desc = result_intf_mgmt['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface']['desc'] mgmt_intf_speed = result_intf_mgmt['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface']['eth_speed'] mgmt_intf_duplex = result_intf_mgmt['ins_api']['outputs']['output']['body'][ 'TABLE_interface']['ROW_interface']['eth_duplex'] device_make = result_hardware['ins_api']['outputs']['output']['body'][ 'chassis_id']