def crawlDevice(ip_address,user,pw): sw1 = Device(ip=ip_address, username=user, password=pw) sw1.open() # Getting everything into dicts sh_vrf = get_vrf(sw1) int_brief = get_ip_int_b(sw1) int_status = get_int_status(sw1) hostname,proccesor_ID,version = get_hostname_serial_version(sw1) neighbors = get_cdp_info(sw1) port_channels = get_portchannel_sum(sw1) # Adding all data into objs LocalDevice = root_Device(hostname,proccesor_ID,version,ip_address,user,pw) for singleVrf in sh_vrf: vrf = Vrf(singleVrf["vrf-name-out"]) if "TABLE_prefix" in singleVrf["TABLE_addrf"][ "ROW_addrf"].keys(): for prefixes in singleVrf["TABLE_addrf"][ "ROW_addrf"]["TABLE_prefix"]["ROW_prefix"]: vrf.addPrefix(prefixes["ipprefix"]) LocalDevice.addVrf(vrf) for ipInter in int_brief: LocalDevice.addIp(ipInter["ROW_intf"]["prefix"]) LocalDevice.addPortChannel(port_channels) for interface in int_status: LocalDevice.addIp(interface) for neighbor in neighbors: neighEntry = Neighbors(root_Device,neighbor) LocalDevice.addNeighbor(neighEntry) return LocalDevice
def main(): '''Call the show_ip_int_brief function and read in from file''' #check they entered a filename if len(sys.argv) <= 1: print "You must enter a filename: int_brief.py <filename>" sys.exit() else: #check if the file name is correct and can be opened try: script, filename = sys.argv with open(filename, 'r') as fp: #with will close file for line in fp: #loop through the lines switch_admin = [] if len(line.split()) == 3: #check if there are three variables per line for word in line.split(): #loop through the words and add them to a list #fill a list with the items in the line - should be three switch_admin.append(word) #create the switch object switch = Device(ip=switch_admin[0], username=switch_admin[1], password=switch_admin[2]) switch.open() #call the function show_ip_int_brief(switch, switch_admin[0]) else: print "Your file variables are incorrect. It should be <ip address> <username> <password> per line." sys.exit() except IOError: print "Your file was mistyped! Please try again." sys.exit()
def main(): switch = Device(ip='172.31.217.136', username='******', password='******') switch.open() show_boot_config = copy_bootflash(switch) print show_boot_config
def main(): ''' Main loop to retrieve data :return: ''' args = getargs() username = args.user if not username: username = raw_input("Device Username:") password = getpass.getpass('Device password:'******'ip' ) print 'Traffic flowing from %s to %s will use physical interface %s' % (args.source, args.destination, result)
def main(): switch = Device(ip='172.31.217.133',username='******',password='******') switch.open() mac_table = get_mac(switch) arp_table = get_arp(switch) print "Will parse the following MAC and ARP tables obtained from the switch:" print json.dumps(mac_table, indent=4) print json.dumps(arp_table, indent=4) # Loop through the MAC address table for mac_entry in mac_table: # If the MAC address is present in the ARP table if mac_entry in arp_table: #Attempt name resolution. gethostbyaddr will throw an exception if host is not found try: ip_address = arp_table[mac_entry] interface_name = mac_table[mac_entry] hostname = gethostbyaddr(ip_address) print hostname[0] + " (" + ip_address + ") is on " + interface_name # Pass the result to write_descript to apply the hostname to the NX-OS interface write_descript(switch,interface_name,hostname[0]) except: # For simplicity, we will assume that any exception is a host not found and move on print "No hostname for " + ip_address + " was found... skipping"
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 main(): switch = Device(ip='172.23.193.210', username='******', password='******') switch.open() checkroutes(switch) stp_detail(switch) protocols = get_ip_protocols(switch) for proto in protocols: print "Switch is running " + proto ospf_interfaces = [] eigrp_interfaces = [] bgp_interfaces = [] if "ospf" in protocols: ospf_interfaces = get_ospf_interfaces(switch) if "eigrp" in protocols: eigrp_interfaces = get_eigrp_interfaces(switch) if "bgp" in protocols: bgp_interfaces = get_bgp_interfaces(switch) if len(ospf_interfaces) >= 1: print "OSPF has peers on interface(s): " + str(ospf_interfaces) if len(eigrp_interfaces) >= 1: print "EIGRP has peers on interface(s): " + str(eigrp_interfaces) if len(bgp_interfaces) >= 1: print "BGP has peers on interface(s): " + str(bgp_interfaces) vpc_vlan_list = get_vpc_vlans(switch) check_vlan_vpc(ospf_interfaces, vpc_vlan_list) check_vlan_vpc(eigrp_interfaces, vpc_vlan_list) check_vlan_vpc(bgp_interfaces, vpc_vlan_list)
def main(): switch = Device(ip='172.23.193.210', username='******', password='******') switch.open() checkroutes(switch) get_ip_protocols(switch) stp_detail(switch)
def main(ip_addr): print "Gathering files, please wait" switch = Device(ip = ip_addr, username = '******', password = '******') switch.open() sh_version=fn_sh_version(switch) sh_interface=fn_sh_interface(switch) sh_vlan=fn_sh_vlan(switch) sh_int_swports=fn_sh_int_swports(switch) sh_port_chan_sum=fn_sh_port_chan_sum(switch)
def getneighbors(ip,username,password): devices = [ ip ] devicecount=0 while devicecount != len(devices): dev = Device(ip=devices[devicecount], username=username, password=password) dev.open() devices = devices + show_cdwneighbors(dev,devices) devicecount+=1 return devices
def main(): switch = Device(ip='172.31.217.134', username='******', password='******') switch.open() ver = show_dev_version(switch) print json.dumps(ver, indent=4) ver_check = check_version(switch)
def connect_pulldata(ipaddr, uname, pword): switch = Device(ip=ipaddr, username=uname, password=pword) switch.open() vtp_facts = ipaddr + ',' + vtp_info(switch) csvwriter = csv.writer(open("vtp.csv", "a")) csvwriter.writerow([vtp_facts])
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 mon_device(device,seconds,tabs,destinationIp): threadQueue.put(1) destIp = destinationIp tabs = tabs*2 deviceIp = device.connectedOn username = device.username passwor = device.password sw1 = Device(ip=deviceIp, username=username, password=passwor) sw1.open() flag = True print "Monitoring:",deviceIp try: while flag: allPack = [] interfacers = get_int(sw1) device.updateInterfaceCounters(interfacers) for i in interfacers: x = interface(i["interface"]) x.populateCounters(i) #if x.eth_giants > 0 or x.eth_jumbo_inpkts > 0 or x.eth_crc > 0 or x.eth_giants or x.eth_inerr: if x.eth_outpkts > 1000: print ("-" * tabs)+ "Over 1000 on ", x.interface, x.eth_outpkts,deviceIp create_span = sw1.conf(" conf t ; monitor session 30 type erspan-source ; description ERSPAN30 for TEST ; source interface " + x.interface + " both ; destination ip " + destIp + " ; vrf default ; erspan-id 30 ; ip ttl 64 ; ip prec 0 ; ip dscp 0 ; mtu 1500 ; header-type 2 ; no shut ; end ;") print ("-" * tabs) + "Beginning erspan for", seconds ,"seconds","to",deviceIp,"on int",x.interface time.sleep(10) print ("-" * tabs) + "Done capturing, now Cleaning config",deviceIp,"on int",x.interface clean = sw1.conf("config t ;" + " no monitor session 30 ; end") clearing_counters = sw1.conf("clear counters interface" + x.interface) print ("-" * tabs) + "Done Cleaning, erspan sent to", destIp, "from",deviceIp, "-", x.interface # Remove flag for continous moitoring, with flag on it stops after the interface is noticed #flag = False else: allPack.append([x.eth_outpkts,x.interface]) # if x.state == "up" and "Ether" in x.interface: # print x.interface, x.state, x.eth_outpkts time.sleep(3) ints = [] interf = [] for i in allPack: ints.append(i[0]) interf.append(i[1]) maxInt = max(ints) maxInterface = interf[ints.index(maxInt)] print ("-" * tabs) + "Highest packet count is", maxInt, "that is under 1000 on",maxInterface except (KeyboardInterrupt, SystemExit): print ("-" * tabs) + "Keyboard Interrupt, Forcing cleaning of",deviceIp clean = sw1.conf("config t ;" + " no monitor session 30 ; end") print ("-" * tabs) + "Done Cleaning, erspan sent to", destIp, "from",deviceIp, queue.put("RANDOM DATA FOR QUEUE") threadQueue.get(False, 2)
def main(): args = sys.argv if len(args) == 4: switch = Device(ip=args[1], username=args[2], password=args[3]) try: switch.open() interface = show_interface(switch) except: print "\nshow-simple-inventory.py: Please review your input parameters." else: print "\nshow-simple-inventory.py: Invalid Key.\nSyntax: show-simple-inventory.py <switch-name> <username> <password>\n"
def main(): args = sys.argv sw1 = Device(ip='172.31.217.134', username='******', password='******') sw1.open() hardware = get_hardware(sw1) mgmt = get_mgmt(sw1) facts = dict(hardware, **mgmt) if len(args) == 1: print json.dumps(facts, indent=4) elif args[1] in facts: print args[1].upper() + ":", json.dumps(facts[args[1]], indent=4) else: print "Invalid Key. Try again."
def main(): args = sys.argv if len(args) == 5: switch = Device(ip=args[1], username=args[2], password=args[3]) interface_name = args[4] # Get the interface name try: switch.open() cdp = show_cdp(switch, interface_name) print cdp except: print "\nshow-cdp-inventory-interface.py: Please review your input parameters.\n\nSyntax: show-cdp-inventory-interface.py <switch-name> <username> <password> <interface_name>\n" else: print "\nshow-cdp-inventory-interface.py: Invalid Key.\nSyntax: show-cdp-inventory-interface.py <switch-name> <username> <password> <interface_name>\n"
def main(): args = sys.argv if len(args) == 5: switch = Device(ip=args[1], username=args[2], password=args[3]) try: switch.open() showcommand = show_command(switch, args[4]) print showcommand except: print "\nshow-command_v2.py: Please review you input parameters.\n\nSyntax: show-command.py <switch-name> <username> <password> <show-command>\n" else: print "\nshow-command_v2.py: Invalid Key.\nSyntax: show-command.py <switch-name> <username> <password> <show-command>\n"
def main(): print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" ip = raw_input("Enter IP Address of first device: ") username = raw_input("Enter Username: "******"Enter Password: "******"Unable to login to the device" pass
def main(): args = sys.argv sw1 = Device(ip='172.31.217.134', username='******', password='******') sw1.open() hardware = get_hardware(sw1) mgmt = get_mgmt(sw1) facts = dict(hardware, **mgmt) if len(args) == 1: print json.dumps( facts, indent=4) elif args[1] in facts: print args[1].upper() + ":", json.dumps(facts[args[1]], indent=4) else: print "Invalid Key. Try again."
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
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 conf_intfs(conf_dict): ''' This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. params: conf_dict (dictionary), example: { "switch_ip": "172.31.217.135", "intf_desc": "Configured by NXAPI", "intf_id": [ "Ethernet1/1", "Ethernet1/2" ], "vlan_id": "31" } ''' config_changes_list = "" switch_user = '******' switch_pw = 'cisco123' switch_ip = conf_dict['switch_ip'] switch_name = get_switchname(switch_ip) # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse data in to commands for item in range(len(conf_dict['intf_id'])): change_vlan = 'config t ; interface ' + conf_dict['intf_id'][ item] + ' ; switchport access vlan ' + conf_dict['vlan_id'] change_desc = 'config t ; interface ' + conf_dict['intf_id'][ item] + ' ; description ' + conf_dict['intf_desc'] # Send switch commands to NXAPI switch.conf(change_vlan) switch.conf(change_desc) # Generate NXOS-friendly config to return to consumer config_changes_list += show_run(switch_ip, conf_dict['intf_id'][item]) # Log cli_conf call to local file logtime = get_time() log_change(logtime + ': ' + switch_name + '(' + switch_user + '): ' + change_vlan + '\n') log_change(logtime + ': ' + switch_name + '(' + switch_user + '): ' + change_desc + '\n') return config_changes_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_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 conf_intfs(conf_dict): """ This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. params: conf_dict (dictionary), example: { "switch_ip": "172.31.217.135", "intf_desc": "Configured by NXAPI", "intf_id": [ "Ethernet1/1", "Ethernet1/2" ], "vlan_id": "31" } """ config_changes_list = "" switch_user = "******" switch_pw = "cisco123" switch_ip = conf_dict["switch_ip"] switch_name = get_switchname(switch_ip) # Connect to switch switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() # Parse data in to commands for item in range(len(conf_dict["intf_id"])): change_vlan = ( "config t ; interface " + conf_dict["intf_id"][item] + " ; switchport access vlan " + conf_dict["vlan_id"] ) change_desc = "config t ; interface " + conf_dict["intf_id"][item] + " ; description " + conf_dict["intf_desc"] # Send switch commands to NXAPI switch.conf(change_vlan) switch.conf(change_desc) # Generate NXOS-friendly config to return to consumer config_changes_list += show_run(switch_ip, conf_dict["intf_id"][item]) # Log cli_conf call to local file logtime = get_time() log_change(logtime + ": " + switch_name + "(" + switch_user + "): " + change_vlan + "\n") log_change(logtime + ": " + switch_name + "(" + switch_user + "): " + change_desc + "\n") return config_changes_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 conf_intfs(conf_dict): ''' This connects to the chosen switch and gets all of the ports. and vlans. This is filtered to access ports only. ''' config_changes_list = "" switch_user = '******' switch_pw = 'cisco123' switch_ip = conf_dict['switch_ip'] switch = Device(ip=switch_ip, username=switch_user, password=switch_pw) switch.open() for item in range(len(conf_dict['intf_id'])): change_vlan = 'config t ; interface ' + conf_dict['intf_id'][item] + ' ; switchport access vlan ' + conf_dict['vlan_id'] change_desc = 'config t ; interface ' + conf_dict['intf_id'][item] + ' ; description ' + conf_dict['intf_desc'] switch.conf(change_vlan) switch.conf(change_desc) config_changes_list += show_run(switch_ip, conf_dict['intf_id'][item]) return config_changes_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_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 main(): switch = Device(ip='172.31.217.133', username='******', password='******') switch.open() facts = {} intf = show_intf_mgmt(switch) facts['mgmt_intf'] = intf hw = show_hardware(switch) facts.update(hw) args = sys.argv if len(args) == 1: print json.dumps(facts, indent=4) else: if args[1] in facts.keys(): print args[1].upper() + ': ' + json.dumps(facts[args[1]], indent=4) else: print 'Invalid Key. Try again.'
def main(): ''' Main loop to retrieve data :return: ''' # args = getargs() # # username = args.user # # if not username: # username = raw_input("Device Username:") # password = getpass.getpass('Device password:'******'10.1.0.2', username='******', password='******') switch.open() print quarantine(switch)
def main(): switch = Device(ip = '172.31.217.136', username = '******', password = '******') switch.open() #verify = verify_code(switch) #hw = show_hardware(switch) conf = copy_config(switch) bootvar = set_bootvar(switch) #my_vars = yaml.load(file('codeMapMD5.yml','r')) #check OS Version vs. control OS Version in YAML file #print 'Does ' + hw['OS Version'] + ' match ' + my_vars['n9kCodeVer'] #the next four lines are used to check variable types for conversations as needed #print 'my_vars type: ' #print type(my_vars['n9kCodeVer']) #print 'hw type: ' #print type(hw['OS Version']) #change unicode to string for hw['OS Version'] #osVer = unicodedata.normalize('NFKD', hw['OS Version']).encode('ascii','ignore') #print osVer type to check if it's a string, which it is #print 'osVer type: ' #print type(osVer) ''' next two lines are a bad attempt to change osVer into an int. Firstly, we needs more string manipulation by splitting the osVer string on periods and parenthesis, then converting each of those individual strings to ints for comparison ''' #osVerI = int("osVer") #print osVerI #for each in my_vars['NX9000']: # if hw['OS Version'] == my_vars['NX9000.n9kCodeVer']: # print 'Does not need upgrade, checking MD5 Hash' # elif hw['OS Version'] != my_vars['NX9000.n9kCodeVer']: # sw.conf('copy usb0:/'+ my_vars['NX9000.n9kFile'] + 'bootflash:') # print 'Copying files to device...' # else: # print 'Need to upgrade OS version' '''
def main(): switch = Device(ip = '172.31.217.137', username = '******', password = '******') switch.open() verify = verify_code(switch) hw = show_hardware(switch) my_vars = yaml.load(file('codeMapMD5.yml','r')) #check OS Version vs. control OS Version in YAML file #print 'Does ' + hw['OS Version'] + ' match ' + my_vars['n9kCodeVer'] #the next four lines are used to check variable types for conversations as needed #print 'my_vars type: ' #print type(my_vars['n9kCodeVer']) #print 'hw type: ' #print type(hw['OS Version']) #change unicode to string for hw['OS Version'] osVer = unicodedata.normalize('NFKD', hw['OS Version']).encode('ascii','ignore') #print osVer type to check if it's a string, which it is #print 'osVer type: ' #print type(osVer) ''' next two lines are a bad attempt to change osVer into an int. Firstly, we needs more string manipulation by splitting the osVer string on periods and parenthesis, then converting each of those individual strings to ints for comparison ''' #osVerI = int("osVer") #print osVerI if hw['OS Version'] == my_vars['n9kCodeVer']: print 'Does not need upgrade, checking MD5 Hash' #if-else logic for checking MD5 has will go here else: print 'Need to upgrade OS version' '''
def main(): switch = Device(ip='172.31.217.135', username='******', password='******') switch.open() facts = {} intf = sh_int_mgmt(switch) facts['mgmt_intf'] = intf hw = sh_hw(switch) facts.update(hw) args = sys.argv if len(args) == 1: print json.dumps(facts, indent=4) else: if args[1] in facts.keys(): print args[1].upper() + ': ' + json.dumps(facts[args[1]], indent=4) else: print 'Invalid Key. Please provide a valid "key" and try again'
def main(): switch = Device(ip='192.168.200.50') switch.open() facts = {} intf = show_intf_mgmt(switch) facts['mgmt_intf'] = intf hw = show_hardware(switch) facts.update(hw) args = sys.argv if len(args) == 1: print json.dumps(facts, indent=4) else: if args[1] in facts.keys(): print args[1].upper() + ': ' + json.dumps(facts[args[1]],indent=4) else: print 'Invalid Key. Try again.'
def main(): switch = Device(ip='172.31.217.136', username='******', password='******') switch.open() #verify = verify_code(switch) #hw = show_hardware(switch) conf = copy_config(switch) bootvar = set_bootvar(switch) #my_vars = yaml.load(file('codeMapMD5.yml','r')) #check OS Version vs. control OS Version in YAML file #print 'Does ' + hw['OS Version'] + ' match ' + my_vars['n9kCodeVer'] #the next four lines are used to check variable types for conversations as needed #print 'my_vars type: ' #print type(my_vars['n9kCodeVer']) #print 'hw type: ' #print type(hw['OS Version']) #change unicode to string for hw['OS Version'] #osVer = unicodedata.normalize('NFKD', hw['OS Version']).encode('ascii','ignore') #print osVer type to check if it's a string, which it is #print 'osVer type: ' #print type(osVer) ''' next two lines are a bad attempt to change osVer into an int. Firstly, we needs more string manipulation by splitting the osVer string on periods and parenthesis, then converting each of those individual strings to ints for comparison ''' #osVerI = int("osVer") #print osVerI #for each in my_vars['NX9000']: # if hw['OS Version'] == my_vars['NX9000.n9kCodeVer']: # print 'Does not need upgrade, checking MD5 Hash' # elif hw['OS Version'] != my_vars['NX9000.n9kCodeVer']: # sw.conf('copy usb0:/'+ my_vars['NX9000.n9kFile'] + 'bootflash:') # print 'Copying files to device...' # else: # print 'Need to upgrade OS version' '''
def main(): switch = Device(ip='172.31.217.134', username='******', password='******') switch.open() facts = {} intf = show_intf_mgmt(switch) facts['mgmt_intf'] = intf hw = show_hardware(switch) facts.update(hw) args = sys.argv if len(args) == 1: print json.dumps(facts, indent=4) else: if args[1] in facts.keys(): print args[1].upper() + ': ' + json.dumps(facts[args[1]], indent=4) else: print 'Invalid key. Try again.'
def main(): switch = Device(ip='192.168.200.50') switch.open() facts = {} intf = show_intf_mgmt(switch) facts['mgmt_intf'] = intf hw = show_hardware(switch) facts.update(hw) args = sys.argv if len(args) == 1: print json.dumps(facts, indent=4) else: if args[1] in facts.keys(): print args[1].upper() + ': ' + json.dumps(facts[args[1]], indent=4) else: print 'Invalid Key. Try again.'
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
def main(): sw1 = Device(ip='198.18.134.140', username='******', password='******') args = sys.argv if len(args) == 3: interface_name = args[1] try: sw1.open() intf = show_intf(sw1, args[1]) print args[2].upper() + ': ' + json.dumps(intf[args[2]], indent=4) except: #exception for incorrect fact argument print 'Invalid interface parameter specified - argument #2' for k, v in intf.iteritems(): print k else: #else for incorrect augments print 'Review input parameters - Ethernet1/X first and interface parameter second'
def main(): args = sys.argv if len(args) == 5: #This section will check to see if the file pass to Python in a argument actually exists if os.path.exists(args[2]): switch_ips = open(args[2]).read().splitlines() #print switch_ips else: print 'File ', os.path.realpath( args[2]), 'does not exist. Please try again' sys.exit(1) for switch_ip in switch_ips: switch = Device(ip=switch_ip, username=args[3], password=args[4]) switch.open() hw = show_hardware(switch) show_mac_addr(switch, args[1]) else: print 'ERROR: Invalid syntax\n'\ 'Example: \"python findMac.py xxxx.xxxx.xxxx file.txt username password\"' sys.exit(1)
def mon_device(device): threadQueue.put(1) deviceIp = device.connectedOn username = device.username passwor = device.password sw1 = Device(ip=deviceIp, username=username, password=passwor) sw1.open() flag = True print "Monitoring:",deviceIp while flag: allPack = [] interfacers = get_int(sw1) device.updateInterfaceCounters(interfacers) for i in interfacers: x = interface(i["interface"]) x.populateCounters(i) #if x.eth_giants > 0 or x.eth_jumbo_inpkts > 0 or x.eth_crc > 0 or x.eth_giants or x.eth_inerr: if x.eth_outpkts > 1000: print "Over 1000 on ", x.interface, x.eth_outpkts,deviceIp conf = sw1.conf("config t ; ip access-list MonACLTemp ; permit ip any any log ;" + "int " + x.interface + " ; ip access-group MonACLTemp in ; end ; ethanalyzer local interface inband write bootflash:test.cap ") print "\tBeginning Cap for 1 min",deviceIp time.sleep(10) print "\tDone capturing, now Cleaning config",deviceIp clean = sw1.conf("config t ;" + " int " + x.interface + " ; no ip access-group MonACLTemp in ; exit ; no ip access-list MonACLTemp ; end") clearing_counters = sw1.conf("clear counters interface" + x.interface) # Remove flag for continous moitoring, with flag on it stops after the interface is noticed flag = False else: allPack.append(x.eth_outpkts) # if x.state == "up" and "Ether" in x.interface: # print x.interface, x.state, x.eth_outpkts time.sleep(3) print max(allPack), "highest packet count number under 1000 on",deviceIp queue.put("RANDOM DATA FOR QUEUE") threadQueue.get(False, 2) print "Done Cleaning, capture at bootflash:test.cap", deviceIp
# Enter via raw_input N9K IP & User/Password Info # n9k_ip = raw_input("Enter N9K IP Address:") n9k_user = raw_input("Username:"******"Password:"******"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 = {}
file_list = sys.argv 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:
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()