def template(self, args, config, logger): dev_id_list = [] address_list = [] try: file = open(os.path.join(args.file_name), "r") for ip in file: dev_id = self.find.dev_id(args, config, ip, logger) time.sleep(1) dev_id_list.append({"targetDeviceID": "{}".format(dev_id)}) address_list.append({"address": "{}".format(ip.strip())}) file.close() except FileNotFoundError: print("##### ERROR iplist files not found #####") except Exception as err: print("##### ERROR with processing:{} #####".format(err)) # require 'yes' input to proceed # logger.info('Activate BAS on switch INTERFACE {} using VLAN: {}'.format(found_int['name'], args.vlan)) # response = input("Confirm action of changing VLAN ('yes'):") # if not response == 'yes': # logger.info('Did not proceed with change.') # sys.exit(1) # invoke API call to change VLAN sw_api_call = Switch(config, logger) # create API switch call object # push API_CALL_conf_if_bas template out. Update this to use a shared template, the same as change vlan? job_id = sw_api_call.conf_template(dev_id_list, args.template_name) timeout = time.time() + 30 # 30 second timeout starting now time.sleep( 1 ) # without the sleep the job_complete can balk, not finding the job_id yet while not sw_api_call.job_complete(job_id): time.sleep(5) if time.time() > timeout: logger.critical( "Template push failed. Prime job not completed") sys.exit(1) ###################Only sync successful? self.force_sync_multiple(address_list, sw_api_call) # 20 minute timeout ################# if not sw_api_call.job_successful(job_id): logger.critical("Template push failed. Prime job not successful") sys.exit(1) logger.info("Synchronizing ...") # logger.info("Synchronized!") logger.info('Template push complete.') return args
def dev_id(self, args, config, ipaddr, logger): # 400 critical error is thrown if description is not found api_call = Switch(config, logger) # check address to see if hostname or IP if "-" in ipaddr: dev_id = api_call.id_by_hostname(ipaddr.strip()) else: dev_id = api_call.id_by_ip(ipaddr.strip()) return dev_id
def vlanmap_edge(self, args, config, logger): # Version 0.8 - still messy api_call = Switch(config, logger) dev_id_list = api_call.ids_by_location(args.building_filter) self.no_results(dev_id_list) # Exit if 0 results self.csv_printer( ['Device List', 'VLAN ID', 'VLAN Name', 'Connected', 'Configured'], args.csv, logger) vlan_total = {} t_up, t_down = 0, 0 for curr_id in dev_id_list: inventory_dto = api_call.json_detailed(curr_id) time.sleep(1) device_detail = self.device_dictionary(inventory_dto) device_detail, access_error = self.vlan_dict( api_call, device_detail) self.sw_list.append(device_detail['Switch 1']['dev_name']) if len(device_detail['Switch 1']['VLANS']) == 0: print('{} VLAN KEYERROR'.format( device_detail['Switch 1']['dev_name'])) continue vlan_map = {} up, down = 0, 0 for switch in device_detail: for vlan in device_detail[switch]['VLANS']: if str(device_detail[switch]['VLANS'] [vlan]) not in vlan_map.keys(): vlan_map[vlan] = {'UP': up, 'DOWN': down} vlan_map[vlan]['UP'] += device_detail[switch]['VLANS'][ vlan]['UP'] vlan_map[vlan]['DOWN'] += device_detail[switch]['VLANS'][ vlan]['DOWN'] vlan_map[vlan]['Name'] = device_detail[switch]['VLANS'][ vlan]['Name'] self.verbose_printer(vlan_map, args.verbose, logger) for vlan in vlan_map: if vlan not in vlan_total.keys(): vlan_total[vlan] = {'Name': [], 'UP': t_up, 'DOWN': t_down} if vlan_map[vlan]['Name'] not in vlan_total[vlan]['Name']: vlan_total[vlan]['Name'].append(vlan_map[vlan]['Name']) vlan_total[vlan]['UP'] += vlan_map[vlan]['UP'] vlan_total[vlan]['DOWN'] += vlan_map[vlan]['DOWN'] print(self.sw_list) for vlan_id in vlan_total: print('{},{},CONNECTED:{},CONFIGURED:{}'.format( vlan_id, vlan_total[vlan_id]['Name'], vlan_total[vlan_id]['UP'], (vlan_total[vlan_id]['UP'] + vlan_total[vlan_id]['DOWN']))) self.csv_printer([ self.sw_list, vlan_id, vlan_total[vlan_id]['Name'], vlan_total[vlan_id]['UP'], (vlan_total[vlan_id]['UP'] + vlan_total[vlan_id]['DOWN']) ], args.csv, logger) print('Job Complete.')
def bas(self, args, config, logger): # find and display (update this call to work) dev_id, found_int, dev_ip = self.find.int(args, config, args.interface, logger) # require 'yes' input to proceed logger.info( 'Activate BAS on switch INTERFACE {} using VLAN: {}'.format( found_int['name'], args.vlan)) response = input("Confirm action of changing VLAN ('yes'):") if not response == 'yes': logger.info('Did not proceed with change.') sys.exit(1) # invoke API call to change VLAN # sw_api_call = Switch(config.username, config.password, config.cpi_ipv4_address, logger) # create API switch call object sw_api_call = Switch(config, logger) # create API switch call object # push API_CALL_conf_if_bas template out. Update this to use a shared template, the same as change vlan? job_id = sw_api_call.conf_if_bas(dev_id, found_int['name'], args.description, args.vlan) timeout = time.time() + 30 # 30 second timeout starting now time.sleep( 1 ) # without the sleep the job_complete can balk, not finding the job_id yet while not sw_api_call.job_complete(job_id): time.sleep(5) if time.time() > timeout: logger.critical("Change VLAN failed. Prime job not completed") sys.exit(1) if not sw_api_call.job_successful(job_id): logger.critical("Change VLAN failed. Prime job not successful") sys.exit(1) logger.info('Change VLAN complete.') ######################################################## #add a verification flag to sync and display after, instead of default? ######################################################## logger.info("Synchronizing ...") self.force_sync(dev_id, dev_ip, sw_api_call, 20, logger) # 20 minute timeout logger.info("Synchronized!") dev_id, found_int, dev_ip = self.find.int(args, config, args.interface, logger) return args
def port_count(self, args, config, logger): # Version 1.0 - works ports_up, ports_down = 0, 0 # Global ports Up / Down for all devices being reported on api_call = Switch(config, logger) dev_id_list = api_call.ids_by_location( args.building_filter ) # API call to get list of devices to be reported on self.no_results(dev_id_list) # Exit if 0 results self.csv_printer([ 'Device Name', 'Building', 'IP Address', 'Serial Number', 'Device Model', 'Stack Size', 'Connected', 'Notconnect', 'Total', '% Used', 'Reachability' ], args.csv, logger) for curr_id in dev_id_list: time.sleep(0.35) # Prevents too many API calls too fast inventory_dto = api_call.json_detailed( curr_id) # API Call for current device ID's inventory details device_detail = self.device_dictionary( inventory_dto) # Populates dictionary with device details self.sw_list.append( device_detail['Switch 1'] ['dev_name']) # This list will contain all devices reported on for switch in device_detail.keys(): up, down = 0, 0 # Ports Up / Down for current device ID for port in device_detail[switch]['ports']: if port['operationalStatus'] == 'UP': up += 1 elif port['operationalStatus'] == 'DOWN': down += 1 if up != 0 and down != 0: utilization = str(round(((up / (up + down)) * 100))) + '%' else: utilization = "unknown" ports_up += up # Appends current ID values to global Up count ports_down += down # Appends current ID values to global Down count self.verbose_printer( "{}({}): {} Connected | {} Notconnect | {} Total".format( device_detail['Switch 1']['dev_name'], device_detail[switch]['serial_number'], up, down, (up + down)), args.verbose, logger) self.csv_printer([device_detail[switch]['dev_name'], ', '.join([device_detail[switch]['dev_name'][:3]]), device_detail[switch]['ip_address'], \ device_detail[switch]['serial_number'], device_detail[switch]['stack_model'], len(device_detail.keys()), up, down, (up + down), \ utilization, device_detail[switch]['reachability']], args.csv, logger) print(self.sw_list) print("{} Connected | {} Notconnect | {} Total".format( ports_up, ports_down, (ports_up + ports_down)))
def test_method(self, args, config, logger): api_call = Client(config, logger) sw_api_call = Switch(config, logger) dev_id = sw_api_call.id_by_ip("172.30.28.246") result = sw_api_call.json_detailed(dev_id) key_list = [ 'queryResponse', 'entity', 0, 'inventoryDetailsDTO', 'ethernetInterfaces', 'ethernetInterface' ] interface_list_of_dicts = self.parse_json.value( result, key_list, logger) for interface_dict in interface_list_of_dicts: for key in interface_dict: # iterating over dict's return keys only if interface_dict[key] == 'GigabitEthernet1/0/1': print(json.dumps(interface_dict, indent=4))
def mac_vlan(self, args, config, logger): # find and display neigh_name, neigh_ip, interface, description, old_vlan, old_vlan_name, addr = \ self.find.mac_client(args, config, logger) # require 'yes' input to proceed logger.info('Change VLAN to: {}'.format(args.vlan)) response = input("Confirm action of changing VLAN ('yes'):") if not response == 'yes': logger.info('Did not proceed with change.') sys.exit(1) # invoke API call to change VLAN sw_api_call = Switch(config, logger) dev_id = sw_api_call.id_by_ip(neigh_ip) job_id = sw_api_call.conf_if_vlan(dev_id, interface, "Access", args.vlan) timeout = time.time() + 30 # 30 second timeout starting now while not sw_api_call.job_complete(job_id): time.sleep(5) if time.time() > timeout: logger.critical("Change VLAN failed. Prime job not completed") sys.exit(1) if not sw_api_call.job_successful(job_id): logger.critical("Change VLAN failed. Prime job not successful") sys.exit(1) logger.info('Change VLAN complete.')
def int(self, args, config, interface, logger): # 400 critical error is thrown if description is not found api_call = Switch(config, logger) # check address to see if hostname or IP if "-" in args.address: dev_id = api_call.id_by_hostname(args.address.strip()) else: dev_id = api_call.id_by_ip(args.address.strip()) dev_result = api_call.json_basic(dev_id) result = api_call.json_detailed(dev_id) key_list = ['queryResponse', 'entity', 0, 'devicesDTO', 'deviceName'] neigh_name = self.parse_json.value(dev_result, key_list, logger) key_list = ['queryResponse', 'entity', 0, 'devicesDTO', 'ipAddress'] tmp = self.parse_json.value(dev_result, key_list, logger) neigh_ip = socket.gethostbyname( tmp) # resolve fqdn to IP. Prime resolves IP if possible dev_interfaces = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['ethernetInterfaces']['ethernetInterface'] found_match = [] for dev_int in dev_interfaces: if dev_int['name'].endswith(interface): found_match = dev_int ###### logger.info("switch name :{}".format(neigh_name)) logger.info("switch ip :{}".format(neigh_ip)) self.desc_printer(found_match, "interface :", 'name', logger) self.desc_printer(found_match, "description :", 'description', logger) self.desc_printer(found_match, "vlan :", 'accessVlan', logger) self.desc_printer(found_match, "voice vlan :", 'voiceVlan', logger) self.desc_printer(found_match, "mac address :", 'macAddress', logger) self.desc_printer(found_match, "status :", 'operationalStatus', logger) self.desc_printer(found_match, "port mode :", 'desiredVlanMode', logger) self.desc_printer(found_match, "allowed vlans :", 'allowedVlanIds', logger) self.desc_printer(found_match, "speed :", 'speed', logger) self.desc_printer(found_match, "duplex :", 'duplexMode', logger) return dev_id, found_match, neigh_ip
def vlanmap(self, args, config, logger): # Version 0.8 - still messy ba_dict = {} api_call = Switch(config, logger) dev_id_list = api_call.ids_by_location(args.building_filter) self.no_results(dev_id_list) # Exit if 0 results #temp anc = [ 'ASP-RB-4ZZ-01.edgenet.ualberta.ca', 'ECP-KIOSK-01.edgenet.ualberta.ca', 'ECV1-TR-01.edgenet.ualberta.ca', 'ECV2-TR-01.edgenet.ualberta.ca', 'ECV2-TR-02.edgenet.ualberta.ca', 'ECV3-TR-01.edgenet.ualberta.ca', 'ECV4-TR-01.edgenet.ualberta.ca', 'ECV7-TR-01.edgenet.ualberta.ca', 'ECV8-TR-01.edgenet.ualberta.ca', 'ECV9-TR-210-01.edgenet.ualberta.ca', 'ECV9-TR-247-01.edgenet.ualberta.ca', 'ECV9-TR-410-01.edgenet.ualberta.ca', 'ECV9-TR-447-01.edgenet.ualberta.ca', 'H33-TR-B01-01.edgenet.ualberta.ca', 'HUB-RB-9104-01.edgenet.ualberta.ca', 'HUB-RB-9209-01.edgenet.ualberta.ca', 'HUB-RB-RVSL-01.edgenet.ualberta.ca', 'INT-TR-120-01.edgenet.ualberta.ca', 'JCP-TR-GATE-01.edgenet.ualberta.ca', 'JCP-TR-KIOSK-01.edgenet.ualberta.ca', 'LIS-RB-1045-01.edgenet.ualberta.ca', 'LIS-RB-2045A-01.edgenet.ualberta.ca', 'LIS-TR-1026-01.edgenet.ualberta.ca', 'TCH-TR-208-01.edgenet.ualberta.ca', 'TCH-TR-258-01.edgenet.ualberta.ca', 'TCH-TR-408-01.edgenet.ualberta.ca', 'TCH-TR-458-01.edgenet.ualberta.ca', 'MAH-TR-025-01.edgenet.ualberta.ca', 'MAH-TR-1103-01.edgenet.ualberta.ca', 'MPL-RB-4ZZ-01.edgenet.ualberta.ca', 'PCH-TR-108-01.edgenet.ualberta.ca', 'PCH-TR-108-02.edgenet.ualberta.ca', 'PLH-RB-352-01.edgenet.ualberta.ca', 'PLH-TR-120a-01.edgenet.ualberta.ca', 'PLH-TR-164a-01.edgenet.ualberta.ca', 'PLH-TR-424-01.edgenet.ualberta.ca', 'SCP-TR-202-01.edgenet.ualberta.ca', 'SCP-TR-202-02.edgenet.ualberta.ca', 'SFH-TR-1056-01.edgenet.ualberta.ca', 'SFH-TR-1063B-01.edgenet.ualberta.ca', 'SFH-TR-1063B-02.edgenet.ualberta.ca', 'TMH-TR-112-01.edgenet.ualberta.ca', 'UTR-TR-111-01.edgenet.ualberta.ca', 'WCP-RB-287-01.edgenet.ualberta.ca', 'WCP-RB-287-02.edgenet.ualberta.ca', 'WCP-TR-207-01.edgenet.ualberta.ca' ] #anc = ['TCH'] #temp for curr_id in dev_id_list: inventory_dto = api_call.json_detailed(curr_id) time.sleep(0.15) device_detail = self.device_dictionary(inventory_dto) try: #temp if any(x in device_detail['Switch 1']['dev_name'] for x in anc): print('skipped') continue #temp if 'ADM353' in device_detail['Switch 1']['dev_name']: continue if 'VAN-RB-' in device_detail['Switch 1']['dev_name']: continue except Exception as err: continue device_detail, access_error = self.vlan_dict( api_call, device_detail) core_switch, core_port, edge_nei = self.core_uplink( api_call, curr_id) #edge_nei.append(device_detail['Switch 1']['dev_name']) for core in core_switch: if core == '269GSB.corenet.ualberta.ca' or core == 'GSB-RM-269-01.corenet.ualberta.ca': core = 'gsb-ef-175-1.corenet.ualberta.ca' if core not in ba_dict.keys(): ba_dict[core] = {} try: for switch in device_detail: for vlan in device_detail[switch]['VLANS']: if vlan not in ba_dict[core].keys(): ba_dict[core][vlan] = { 'Names': [], 'Connected': 0, 'Configured': 0, 'HSRP': core_switch, 'IP Subnet': 'No IP Address', 'Description': 'No Description', 'VRF': 'No VRF', 'Edge Devices': [] } if device_detail[switch]['VLANS'][vlan][ 'Name'] not in ba_dict[core][vlan][ 'Names']: ba_dict[core][vlan]['Names'].append( device_detail[switch]['VLANS'][vlan] ['Name']) ba_dict[core][vlan]['Connected'] += device_detail[ switch]['VLANS'][vlan]['UP'] ba_dict[core][vlan]['Configured'] += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) for hsrp in core_switch: if hsrp != core: ba_dict[core][vlan]['HSRP'] = hsrp ba_dict[core][vlan]['Core Interface'] = core_port #ba_dict[core][vlan]['Edge Switches'] = edge_nei if device_detail['Switch 1'][ 'dev_name'] not in ba_dict[core][vlan][ 'Edge Devices']: ba_dict[core][vlan]['Edge Devices'].append( device_detail['Switch 1']['dev_name']) except Exception as err: continue print(device_detail['Switch 1']['dev_name'] + ' complete.') ba_dict = self.interface_vlan(api_call, ba_dict) self.csv_printer([ 'Core Switch', 'VLAN ID', 'IP Subnet', 'Interface Description', 'VRF', 'Core_port(s)', 'VLAN Name(s)', 'Connected', 'Configured', 'HSRP', 'Edge Switches' ], args.csv, logger) for ba in ba_dict.keys(): for vlan_id in ba_dict[ba].keys(): self.csv_printer([ ba, vlan_id, ba_dict[ba][vlan_id]['IP Subnet'], ba_dict[ba][vlan_id]['Description'], ba_dict[ba][vlan_id]['VRF'], ba_dict[ba][vlan_id]['Core Interface'], ba_dict[ba][vlan_id]['Names'], ba_dict[ba][vlan_id]['Connected'], ba_dict[ba][vlan_id]['Configured'], ba_dict[ba][vlan_id]['HSRP'], ba_dict[ba][vlan_id]['Edge Devices'] ], args.csv, logger)
def service_matrix_per_sn(self, args, config, logger): api_call = Switch(config, logger) dev_id_list = api_call.ids_by_location( args.building_filter ) # API call to get list of devices to be reported on self.no_results(dev_id_list) # Exit if 0 results self.csv_printer( ['Device Name', 'Building', 'IP Address', 'Device Type', 'Device Model(s)', 'Stack Size', 'Stack_ID', \ 'Serial Number(s)', 'Reachability', 'VoIP', 'APs-UP', 'AP-Configured', 'LC-UP', 'LC-Configured', \ 'PoS-UP', 'PoS-Configured', 'Parking-UP', 'Parking-Configured', 'SUTV-UP', 'SUTV-Configured', \ 'WirelessDisplay-UP', 'WirelessDisplay-Configured', 'Connected', 'Notconnect', 'Port Count', \ '% Used'], args.csv, logger) for curr_id in dev_id_list: inventory_dto = api_call.json_detailed( curr_id) # API Call for current device ID's inventory details time.sleep(0.25) device_detail = self.device_dictionary( inventory_dto) # Populates dictionary wil device details self.sw_list.append( device_detail['Switch 1'] ['dev_name']) # This list will contain all devices reported on device_detail, access_error = self.vlan_dict( api_call, device_detail) cdp = api_call.cdp_neighbours( curr_id) # API calls for CDP Neighbors for switch in device_detail: up, down, uws, ap, phone, lc, pos, parking, sutv, kramer = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 # Services for Service Matrix c_ap, c_lc, c_pos, c_parking, c_sutv, c_kramer = 0, 0, 0, 0, 0, 0 if access_error == 'TRUE': ap, lc, pos, parking, sutv, kramer = 'X', 'X', 'X', 'X', 'X', 'X' # Services for Service Matrix c_ap, c_lc, c_pos, c_parking, c_sutv, c_kramer = 'X', 'X', 'X', 'X', 'X', 'X' for port in device_detail[switch]['ports']: if port['operationalStatus'] == 'UP': up += 1 elif port['operationalStatus'] == 'DOWN': down += 1 try: if up != 0 or down != 0: utilization = str(round( ((up / (up + down)) * 100))) + '%' else: utilization = "unknown" except Exception as err: utilization = "unknown" if len(device_detail[switch]['VLANS']) > 0: for vlan in device_detail[switch]['VLANS']: if '-ap' in device_detail[switch]['VLANS'][vlan]['Name'] or 'uws' in \ device_detail[switch]['VLANS'][vlan]['Name'] or 'wireless' in \ device_detail[switch]['VLANS'][vlan]['Name']: ap += device_detail[switch]['VLANS'][vlan]['UP'] c_ap += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'ist_labs' in device_detail[switch]['VLANS'][vlan]['Name'] or 'labs' in \ device_detail[switch]['VLANS'][vlan]['Name']: lc += device_detail[switch]['VLANS'][vlan]['UP'] c_lc += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'debit' in device_detail[switch]['VLANS'][vlan]['Name'] or 'credit' in \ device_detail[switch]['VLANS'][vlan]['Name']: pos += device_detail[switch]['VLANS'][vlan]['UP'] c_pos += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'onecard' in device_detail[switch]['VLANS'][vlan]['Name'] or 'pos' in \ device_detail[switch]['VLANS'][vlan]['Name']: pos += device_detail[switch]['VLANS'][vlan]['UP'] c_pos += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'parking' in device_detail[switch]['VLANS'][vlan][ 'Name']: parking += device_detail[switch]['VLANS'][vlan][ 'UP'] c_parking += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'sutv' in device_detail[switch]['VLANS'][vlan][ 'Name']: sutv += device_detail[switch]['VLANS'][vlan]['UP'] c_sutv += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) if 'kramer' in device_detail[switch]['VLANS'][vlan][ 'Name']: kramer += device_detail[switch]['VLANS'][vlan][ 'UP'] c_kramer += ( device_detail[switch]['VLANS'][vlan]['UP'] + device_detail[switch]['VLANS'][vlan]['DOWN']) for c in cdp: if 'Phone' in c['neighborDevicePlatformType']: for port in device_detail[switch]['ports']: if c['nearEndInterface'] in port['name']: phone += 1 print('{} {} complete.'.format( device_detail[switch]['dev_name'], device_detail[switch]['stack_id'])) self.csv_printer([device_detail[switch]['dev_name'], ', '.join([device_detail[switch]['dev_name'][:3]]), \ device_detail[switch]['ip_address'], device_detail[switch]['dev_type'], \ device_detail[switch]['stack_model'], len(device_detail.keys()), device_detail[switch]['stack_id'], \ device_detail[switch]['serial_number'], device_detail[switch]['reachability'], phone, \ ap, c_ap, lc, c_lc, pos, c_pos, parking, c_parking, sutv, c_sutv, kramer, c_kramer, \ up, down, (up + down), utilization], args.csv, logger)
def service_matrix(self, args, config, logger): building_summary = {} error_list = [] api_call = Switch(config, logger) dev_id_list = api_call.ids_by_location( args.building_filter ) # API call to get list of devices to be reported on self.no_results(dev_id_list) # Exit if 0 results self.csv_printer([ 'Device Name', 'Building', 'IP Address', 'Device Type', 'Device Model(s)', 'Stack', 'Serial Number(s)', 'Reachability', 'UWS', 'VoIP', 'LC', 'PoS', 'Parking', 'SUTV', 'Wireless Display', 'Connected', 'Notconnect', 'Port Count', '% Used', 'Uplink', 'CDP Neighbors', 'SW Ver', 'Management VLAN' ], args.csv, logger) for curr_id in dev_id_list: try: inventory_dto = api_call.json_detailed( curr_id ) # API Call for current device ID's inventory details time.sleep(0.15) device_detail = self.device_dictionary( inventory_dto) # Populates dictionary wil device details self.sw_list.append( device_detail['Switch 1']['dev_name'] ) # This list will contain all devices reported on up, down, ap, phone, lc, pos, parking, sutv, kramer = 0, 0, 0, 0, 0, 0, 0, 0, 0 # Services for Service Matrix print(device_detail['Switch 1']['dev_name'] + ' started.') time.sleep(0.15) vlan_config, int_vlan, vlan_count = self.vlan_names( api_call, device_detail) vlan_names = {} for vlan in vlan_config: vlan_names[vlan[0]] = vlan[1].lower() if vlan[0] in vlan_count.keys(): # counting configured vlans to bypass Prime issues with access vlan in port details if '-lc-' in vlan[1].lower( ) or 'lab' in '-lc-' in vlan[1].lower(): lc += vlan_count[vlan[0]] if 'wirelessdisplay' in vlan[1].lower( ) or 'kramer' in vlan[1].lower(): kramer += vlan_count[vlan[0]] if 'debit' in vlan[1].lower( ) or 'onecard' in vlan[1].lower(): pos += vlan_count[vlan[0]] if 'parking' in vlan[1].lower(): parking += vlan_count[vlan[0]] if 'sutv' in vlan[1].lower(): sutv += vlan_count[vlan[0]] for switch in device_detail: for port in device_detail[switch]['ports']: if port['operationalStatus'] == 'UP': up += 1 elif port['operationalStatus'] == 'DOWN': down += 1 cdp_uplink = [] cdp = api_call.cdp_neighbours( curr_id) # API calls for CDP Neighbors for cdp_curr in cdp: try: if 'AIR' in cdp_curr[ 'neighborDevicePlatformType'] or 'AXI' in cdp_curr[ 'neighborDevicePlatformType']: # Count APs ap += 1 if 'Cisco IP Phone' in cdp_curr[ 'neighborDevicePlatformType']: # Count IP Phones phone += 1 if 'corenet' in cdp_curr[ 'neighborDeviceName'] or 'edgenet' in cdp_curr[ 'neighborDeviceName']: # Populates uplinks if cdp_curr[ 'neighborDeviceName'] not in cdp_uplink: cdp_uplink.append( cdp_curr['neighborDeviceName'] + ': ' + cdp_curr['farEndInterface']) except Exception as err: print('CDP Error') continue if any('-ef-' in s for s in cdp_uplink): core = 'BA' elif any('-ba-' in s for s in cdp_uplink): core = 'BA' elif any('-ds-' in s for s in cdp_uplink): core = 'DS' elif any('edgenet' in s for s in cdp_uplink): core = 'CHAIN' else: core = 'unknown' print(device_detail[switch]['dev_name'] + ' complete.') except Exception as err: error_list.append(curr_id) print('curr_id Report Error') continue try: self.csv_printer([device_detail[switch]['dev_name'], ', '.join([device_detail[switch]['dev_name'][:3]]), \ device_detail[switch]['ip_address'], device_detail[switch]['dev_type'], \ ', '.join(self.stack_models(device_detail)), len(device_detail.keys()), \ ', '.join(self.serial_numbers(device_detail)), device_detail[switch]['reachability'], ap, phone, lc, \ pos, parking, sutv, kramer, up, down, (up + down), \ str(round(((up / (up + down)) * 100))) + '%', core, cdp_uplink, device_detail[switch]['sw_version'], int_vlan], args.csv, logger) except Exception as err: self.csv_printer([device_detail[switch]['dev_name'], ', '.join([device_detail[switch]['dev_name'][:3]]), \ device_detail[switch]['ip_address'], device_detail[switch]['dev_type'], \ ', '.join(self.stack_models(device_detail)), len(device_detail.keys()), \ ', '.join(self.serial_numbers(device_detail)), device_detail[switch]['reachability'], ap, phone, lc, \ pos, parking, sutv, kramer, up, down, (up + down), \ '?', core, cdp_uplink, device_detail[switch]['sw_version'], int_vlan], args.csv, logger) building_code = device_detail[switch]['dev_name'][:3].upper() if building_code not in building_summary.keys(): building_summary[building_code] = {'Up': 0, 'Down': 0} building_summary[building_code]['Up'] += up building_summary[building_code]['Down'] += down else: building_summary[building_code]['Up'] += up building_summary[building_code]['Down'] += down print('Job Complete.') print(error_list)
def core(self, args, config, logger): # 400 critical error is thrown if description is not found api_call = Switch(config, logger) # check address to see if hostname or IP if "-" in args.address: dev_id = api_call.id_by_hostname(args.address.strip()) else: dev_id = api_call.id_by_ip(args.address.strip()) dev_result = api_call.json_basic(dev_id) result = api_call.json_detailed(dev_id) #create list of vlan interfaces (L3 & vlan database) dev_ip_interfaces = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['ipInterfaces']['ipInterface'] dev_vlan_interfaces = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['vlanInterfaces']['vlanInterface'] dev_modules = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['modules']['module'] key_list = ['queryResponse', 'entity', 0, 'devicesDTO', 'deviceName'] neigh_name = self.parse_json.value(dev_result, key_list, logger) key_list = ['queryResponse', 'entity', 0, 'devicesDTO', 'ipAddress'] tmp = self.parse_json.value(dev_result, key_list, logger) neigh_ip = socket.gethostbyname( tmp) # resolve fqdn to IP. Prime resolves IP if possible #####if looking for a port add logic here( search for '/') if "/" in args.search_crit: dev_interfaces = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['ethernetInterfaces'][ 'ethernetInterface'] dev_found_interfaces = [] for dev_int in dev_interfaces: #if values_dict['search_crit'] in dev_int['name']: if dev_int['name'].endswith(args.search_crit): dev_found_interfaces.append(dev_int) ###### logger.info("switch name :{}".format(neigh_name)) logger.info("switch ip :{}".format(neigh_ip)) #dev_module is not working with BA switches #dev_module = self.list_parse_ends(values_dict['search_crit'], 'description', dev_modules, logger) #self.desc_printer(dev_module, "Transciever info :", 'description', logger) #logger.info("---- found {} description match on switch ----".format(len(dev_found_interfaces))) for dev_int in dev_found_interfaces: self.desc_printer(dev_int, "Admin Status :", 'adminStatus', logger) self.desc_printer(dev_int, "Operational Status :", 'operationalStatus', logger) self.desc_printer(dev_int, "Port :", 'name', logger) self.desc_printer(dev_int, "speed :", 'speed', logger) if 'description' in dev_int: self.desc_printer(dev_int, "description :", 'description', logger) if 'desiredVlanMode' in dev_int: if dev_int['desiredVlanMode'] == "ACCESS": self.desc_printer(dev_int, "Switchport Mode :", 'desiredVlanMode', logger) self.desc_printer(dev_int, "Access Vlan :", 'accessVlan', logger) self.vlan(str(dev_int['accessVlan']), dev_vlan_interfaces, dev_ip_interfaces, logger) elif dev_int['desiredVlanMode'] == "TRUNK": self.desc_printer(dev_int, "Switchport Mode :", 'desiredVlanMode', logger) self.desc_printer(dev_int, "Allowed Vlans :", 'allowedVlanIds', logger) elif 'desiredVlanMode' not in dev_int and dev_int[ 'operationalStatus'] == 'UP': logger.info( "This is a routed interface -- future functionality") #dev_vlan = self.vlan_parse(values_dict['search_crit'], dev_vlan_interfaces, dev_ip_interfaces,logger) else: #dev_vlan = self.vlan_parse(values_dict['search_crit'],dev_vlan_interfaces,dev_ip_interfaces,logger) self.vlan(args.search_crit, dev_vlan_interfaces, dev_ip_interfaces, logger) # return result
def desc(self, args, config, logger): # 400 critical error is thrown if description is not found api_call = Switch(config, logger) dev_id_list = api_call.ids_by_desc(args.description.strip('"'), args.name) logger.info( " # of switches with Matching occurrences of \"{}\" found: {} ". format(args.description, len(dev_id_list))) # exit out of loop if no matches if len(dev_id_list) < 1: sys.exit(1) for curr_id in dev_id_list: dev_result = api_call.json_basic( curr_id) # Modify this to go through multiple result = api_call.json_detailed( curr_id) # Modify this to go through multiple logger.info("------- Matching Switch #{}--------".format( dev_id_list.index(curr_id) + 1)) key_list = [ 'queryResponse', 'entity', 0, 'devicesDTO', 'deviceName' ] neigh_name = self.parse_json.value(dev_result, key_list, logger) key_list = [ 'queryResponse', 'entity', 0, 'devicesDTO', 'ipAddress' ] tmp = self.parse_json.value(dev_result, key_list, logger) neigh_ip = socket.gethostbyname( tmp) # resolve fqdn to IP. Prime resolves IP if possible ###########currently working out how to grab items that match values[description]_dict. dev_interfaces = result['queryResponse']['entity'][0][ 'inventoryDetailsDTO']['ethernetInterfaces'][ 'ethernetInterface'] dev_found_interfaces = [] for dev_int in dev_interfaces: if 'description' in dev_int: #currently not working with comma seperated values. Check if each value in #similar to device/ids_by_desc split and remove brackets. abstract function? desc_list = args.description.split(",") # if values_dict['description'] in dev_int['description']: if all(x.casefold() in dev_int['description'].casefold() for x in desc_list): dev_found_interfaces.append(dev_int) ###### logger.info("switch name :{}".format(neigh_name)) logger.info("switch ip :{}".format(neigh_ip)) logger.info( "---- found {} description match on switch ----".format( len(dev_found_interfaces))) for dev_int in dev_found_interfaces: logger.info("---- matching description #{} ----".format( dev_found_interfaces.index(dev_int) + 1)) self.desc_printer(dev_int, "interface :", 'name', logger) self.desc_printer(dev_int, "description :", 'description', logger) self.desc_printer(dev_int, "vlan :", 'accessVlan', logger) self.desc_printer(dev_int, "mac address :", 'macAddress', logger) self.desc_printer(dev_int, "status :", 'operationalStatus', logger) self.desc_printer(dev_int, "port mode :", 'desiredVlanMode', logger) self.desc_printer(dev_int, "allowed vlans :", 'allowedVlanIds', logger) self.desc_printer(dev_int, "speed :", 'speed', logger) self.desc_printer(dev_int, "duplex :", 'duplexMode', logger) return dev_found_interfaces