def ports(conn, sw): hostname = conn.find_prompt() data[hostname] = [] power = conn.send_command("show power inline") interface = parse_output(platform="cisco_ios", command="show interface", data=conn.send_command("show interface")) inter_status = parse_output( platform="cisco_ios", command="show interface status", data=conn.send_command("show interface status")) description = parse_output( platform="cisco_ios", command="show interface description", data=conn.send_command("show interface description")) for value in interface: if "FastEthernet" in value["interface"] or "GigabitEthernet" in value[ "interface"]: if "up" not in value["protocol_status"] and ( (value["last_input"] == "never" and value["last_output"] == "never") or ("y" in value["last_input"] or "y" in value["last_output"])): if "FastEthernet" in value["interface"]: port = value["interface"].replace("FastEthernet", "Fa") elif "GigabitEthernet" in value["interface"]: port = value["interface"].replace("GigabitEthernet", "Gi") if port in power: poe = "PoE" elif port not in power: poe = "No PoE" for value in inter_status: if value["port"] == port: vlan = value["vlan"] status = value["status"] for value in description: if value["port"] == port: descrip = value["descrip"] try: data[hostname].append({ "Hostname": hostname, "Hostaddress": sw, "Port": port, "PoE": poe, "Status": status, "Description": descrip, "VLAN": vlan }) except (UnboundLocalError): pass else: pass print(f"Validacion finalizada --> {hostname}") conn.disconnect()
def cisco_api_command_safe(device, command): #trigger API RunCounter to increment when API is called r = requests.request( "POST", "http://myserver.mydomain.com:5018/api/trigger/Cisco_Provider", verify=False) if command not in valid: raise ValueError("Unsupported Command: must be one of %r." % valid) try: dev_connect = cisco_connector(device) except Exception as e: ret_error = "Exception found:" + str(e) return ret_error try: os = findos(device) result = dev_connect.send_command(command) dev_connect.disconnect() try: output = parse_output(platform=os, command=command, data=result) return jsonify(output) except: output = result return output except Exception as e: ret_error = "Exception found:" + str(e) return ret_error
def show_cisco_commands(a_device, output_q): """ Use Netmiko to execute commands. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_device) hostname = remote_conn.base_prompt ## this line pulls the hostname from the device ## these are the commands being sent to the devices sh_commands = remote_conn.send_command("show int status") sh_commands_parsed = parse_output(platform="cisco_ios", command="show int status", data=sh_commands) print(("=" * 80) + "\n") print((hostname)) print("") ## this for loop looks for the information that is in in sh_commands_parsed variables for i in sh_commands_parsed: if i['vlan'] == '12': intf = (i['port']) vlans = (i['vlan']) status = (i['status']) print('Found port ' + intf, 'on VLAN ' + vlans, "\n" 'Current Port status is: ' + status) print("") print("") print(("=" * 80) + "\n") output_q.put(output_dict)
def parse(data_p): output_parse = parse_output(platform="cisco_ios", command="show ip int br", data=data_p) device_IP = output_parse[0] ip = device_IP["ipaddr"] return ip
def _send_command(self, devices: Nornir, *args, **kwargs): # Variables use_textfsm = False command = "" # Implementation if "command_string" in kwargs: command = kwargs["command_string"] else: command = self.mock_command if "use_textfsm" in kwargs: use_textfsm = kwargs["use_textfsm"] params = { "command_string": command, } # result = devices.run(task=self.__extract_mock_data, **params) result = devices.run(task=self.__extract_mock_data, num_workers=1, **params) for device in result: if use_textfsm and result[device].result != "Timeout": result[device][0].result = parse_output( platform=devices.inventory.hosts[device].platform.split("-")[1], command=command, data=result[device].result, ) return result
def ap_list(request): # Connect to wlc and provide ap list: if request.method == "GET": # Connect to correct controller: ip_address = "{}.{}.{}.{}".format(a, b, c, d) cisco1 = { "ip": ip_address "username": username1, "password": password1, "device_type": "cisco_wlc_ssh", 'global_delay_factor': 4, 'banner_timeout': 7 } net_connect = ConnectHandler(**cisco1) # Send command and get output from controller: command = "show ap summary" output = net_connect.send_command(command) # parse output using ntc_templates: new_output = parse_output(platform="cisco_wlc_ssh", command="show ap summary", data=output) net_connect.disconnect() # render output as {'context': new_output} becouse django dont accept contect as list of dist: return render(request, 'Migration_Website/ap_list.html', {'context': new_output}) if request.method == "POST": # Get selected AP ip_list = request.POST.getlist("ip") # ap saved to list for ap in ip_list: ap_to_migration.append(ap) # redirect to migration page: return redirect('ap_migration')
def import_asns(): if request.method == 'GET': devices = ['DC1-coresw', 'DC2-coresw', 'DC3-coresw'] aslist = [] for dev in devices: device = util.CiscoDeviceRO(host=dev) dev_connect = Netmiko(**device.__dict__) bgp_out = dev_connect.send_command("show ip bgp vrf all all") bgp_parsed = parse_output(platform="cisco_nxos", command="show ip bgp", data=bgp_out) dev_connect.disconnect() print ("Collected BGP table for " + dev) print ('<br />') bgpasns = [ sub['as_path'] for sub in bgp_parsed ] for asn in bgpasns: asnsplit = asn.split() for asnum in asnsplit: if asnum not in aslist and int(asnum) >=64512 and int(asnum) <=65535: aslist.append(asnum) as_map = map(int, aslist) as_sort = sorted(as_map) for sort in as_sort: asn_status = BGP.query.get(sort) if asn_status == None: new_asn = BGP(number=sort, desc='Imported from Core BGP Table') try: db.session.add(new_asn) db.session.commit() except: continue return redirect('/')
def config_int(device): telnet=conn(device) telnet.enable() ############## Cau hinh SSH ####################################### command_1=[ "int e0/0", "no switchport", "ip add dhcp", "no shut" ] command_2=[ "ip domain-name blackdrag0n.pmk", "username admin pass 123", "crypto key ge rsa modul 1024", "line vty 0 4", "login local", "password 123", "transport input ssh" ] #################################################### telnet.send_config_set(command_1) telnet.send_config_set(command_2) data=telnet.send_command("show ip int br",delay_factor=15) parse_data=parse_output(platform="cisco_ios",command="show ip int br",data=data) telnet.disconnect() print("Hoan tat Device No."+str(device["port"]+" co IP: "+parse_data[0]["ipaddr"]))
def show_vlan(device): ssh = ConnectHandler(**device) ssh.enable() data = ssh.send_command("show vlan") data_parse = parse_output(platform="cisco_ios", command="show vlan", data=data) vlan = {} ###vlan={"vlan_ID":"Interfaces"} for i in data_parse: vlan[i["vlan_id"]] = i["interfaces"] if "Et0/2" and "Et0/1" in vlan["1"]: print("vlan 1 da duoc gan cac cong tren") else: print("Vlan 1 chua duoc gan cac cong tren") #print("Day la du lieu duoi dang JSON") pprint(vlan) ''' list_vlan=[] for i in data_parse: list_vlan.append(i["vlan_id"]) if "1" in list_vlan: print("Da co vlan 10") else: print("chua co Vlan 10 , Dang tao vlan 10") ''' #pprint(data_parse) ssh.disconnect()
def check_ver(device): ssh = ConnectHandler(**device) data = ssh.send_command("show ver") data_dict = parse_output(platform="cisco_ios", command="show ver", data=data) '''#Data_dict [{'config_register': '0x2102', 'hardware': ['CSR1000V'], 'hostname': 'CSR1000V', 'mac': [], 'reload_reason': 'Unknown reason', 'rommon': 'IOS-XE', 'running_image': 'packages.conf', 'serial': ['97XPYZH1ERC'], 'uptime': '1 week, 4 days, 19 hours, 36 minutes', 'version': '16.12.3'}] ''' for i in data_dict: if i["version"] <= "16.12.2": print("{} IP {} version hien tai {} can update version".format( i["rommon"], device["ip"], i["version"])) else: print( "{} IP {} version hien tai {} dang o version moi nhat".format( i["rommon"], device["ip"], i["version"])) ssh.disconnect()
def parse(self, *_args, **_kwargs): """ Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: dict :example: The parse function of a parser should return a dict: {"errors": [a list of errors]} or {"parsed": obj} """ cli_output = self._task_args.get("text") res = self._check_reqs() if res.get("errors"): return {"errors": res.get("errors")} platform = res["network_os"] command = res["command"] try: parsed = parse_output(platform=platform, command=command, data=cli_output) return {"parsed": parsed} except Exception as exc: return {"errors": [to_native(exc)]}
def parse_outputs(hostnames: list, command: str) -> None: for hostname in hostnames: with open(f"./configs/{hostname}{command_mapper.get(command)}.raw", "r") as f: parsed_config = parse_output(platform='cisco_ios', command=command, data=f.read()) with open( f"./parsed_configs/{hostname}{command_mapper.get(command)}.parsed", "w") as newfile: newfile.write(json.dumps(parsed_config, indent=4))
def show_version(a_device): """ Execute show version command using Netmiko then parse the output with ntc template """ remote_conn = ConnectHandler(**a_device) sh_ver = remote_conn.send_command_expect("show version") parse_ver = parse_output(platform='cisco_ios', command='show version', data=sh_ver) print(parse_ver[0]['hostname'], parse_ver[0]['version'])
def raw_template_test(raw_file): """Return structured data along with reference data.""" parsed_file = '%s.parsed' % raw_file[:-4] parts = raw_file.split('/') platform = parts[1] command = ' '.join(parts[2].split('_')) with open(raw_file, 'r') as data: rawoutput = data.read() structured = parse_output(platform=platform, command=command, data=rawoutput) with open(parsed_file, 'r') as data: parsed_data = yaml.safe_load(data.read()) return structured, parsed_data['parsed_sample']
def l3data_ios(user,pas,core,l3arp,l3route): for device in core["ios"]: conn = ConnectHandler(device_type="cisco_ios_ssh" ,host=device ,username=user ,password=pas) arp = parse_output(platform="cisco_ios",command="show ip arp",data=conn.send_command(f"show ip arp")) for entry in arp: if entry["interface"] not in l3arp["ios"].keys(): l3arp["ios"][entry["address"]] = {} l3arp["ios"][entry["address"]]["mac"] = entry["mac"] elif entry["interface"] in l3arp["ios"].keys(): pass route = parse_output(platform="cisco_ios",command="show ip route",data=conn.send_command(f"show ip route")) for entry in route: if entry["protocol"] == "C": connected_route = entry["network"] +"/"+ entry["mask"] if connected_route not in l3route["ios"]: l3route["ios"].append(connected_route) elif connected_route in l3route["ios"]: pass elif entry["protocol"] != "C": pass print(f"Data l3 extraida --> {conn.find_prompt()}") conn.disconnect()
def get_facts(self): hostname_output = self.send_commands("show hostname | json")[0]["show hostname | json"] version_output = self.send_commands("show version | json")[0]["show version | json"] interface_output = self.send_commands("show interfaces")[0]["show interfaces"] interface_parsed = parse_output(platform="arista_eos", command="show interfaces", data=interface_output) self.hostname = json.loads(hostname_output)["hostname"] self.fqdn = json.loads(hostname_output)["fqdn"] self.mac_address = json.loads(version_output)["systemMacAddress"] self.serial_number = json.loads(version_output)["serialNumber"] self.eos_version = json.loads(version_output)["version"] self.model = json.loads(version_output)["modelName"] self.chipset = switchModelInfo["-".join(json.loads(version_output)["modelName"].split("-")[:3])]["chipset"] self.interfaces = interface_parsed
def rollback(vlan, network): """interface commands to delete and bgp configurations""" commands = ['no interface vlan{}'.format(vlan), "no vlan {}".format(vlan)] net_connect.send_config_set(commands) bgp_sum = net_connect.send_command('show ip bgp summary') bgp_parsed = parse_output(platform='cisco_ios', command='show ip bgp summary', data=bgp_sum) for item in bgp_parsed: local = item.get('local_as') bgp_config = ['router bgp {}'.format(local), 'address-family ipv4', 'no network{}'.format(network)] net_connect.send_config_set(bgp_config)
def bgp_cfg(network): """cli output is parsed into a dictionary from returned text variables set for bgp configuration structure""" bgp_sum = net_connect.send_command('show ip bgp summary') bgp_parsed = parse_output(platform='cisco_ios', command='show ip bgp summary', data=bgp_sum) for item in bgp_parsed: local = item.get('local_as') bgp_config = ['router bgp {}'.format(local), 'address-family ipv4 unicast', 'network {} route-map SET-CORE-COMMUNITY'.format(network)] net_connect.send_config_set(bgp_config) print(net_connect.send_command('show run | sec bgp'))
def show_vlan(device,id_vlan): ssh=ConnectHandler(**device) ssh.enable() data=ssh.send_command("show vlan") data_parse=parse_output(platform="cisco_ios",command="show vlan",data=data) ''' ###data_parse output### [{'interfaces': ['Et0/1', 'Et0/2', 'Et0/3'], 'name': 'default', 'status': 'active', 'vlan_id': '1'}, {'interfaces': [], 'name': 'fddi-default', 'status': 'act/unsup', 'vlan_id': '1002'}, {'interfaces': [], 'name': 'token-ring-default', 'status': 'act/unsup', 'vlan_id': '1003'}, {'interfaces': [], 'name': 'fddinet-default', 'status': 'act/unsup', 'vlan_id': '1004'}, {'interfaces': [], 'name': 'trnet-default', 'status': 'act/unsup', 'vlan_id': '1005'}] ''' vlan={} ###Command access_int=["int range e0/1-2","switchport access vlan " + id_vlan] ###tao ra tu dien co dang vlan={"vlan_ID":"Interfaces"} for i in data_parse: vlan[i["vlan_id"]]=i["interfaces"] ###Tao ham kiem tra interface cua vlan try: if "Et0/2" and "Et0/1" in vlan[id_vlan]: print("vlan {} da duoc gan cac cong e0/1 va e0/2".format(id_vlan)) ssh.disconnect() else: print("Vlan {} chua duoc gan cac cong e0/1 va e0/2".format(id_vlan)) print(ssh.send_config_set(access_int)) print(ssh.send_command("show vlan br")) ssh.disconnect() except KeyError: #Neu vlan id ko co trong tu dien vlan o tren se bao loi KeyError print("Khong co vlan tien hanh tao vlan va gan cong") print(ssh.send_config_set(access_int)) print(ssh.send_command("show vlan br")) ssh.disconnect()
def raw_template_test(raw_file): """Return structured data along with reference data.""" parsed_file = "{0}.parsed".format(raw_file[:-4]) parts = raw_file.split("/") platform = parts[1] command = " ".join(parts[2].split("_")) with open(raw_file, "r") as data: rawoutput = data.read() structured = parse_output(platform=platform, command=command, data=rawoutput) with open(parsed_file, "r") as data: parsed_data = yaml.safe_load(data.read()) return structured, parsed_data["parsed_sample"]
def get_cdp_neighbors(self, mgmt_ip, hostname): self.print_connecting(hostname) try: cmd = "show cdp neighbors detail" with ConnectHandler(device_type='cisco_ios', host=mgmt_ip, username=self.username, password=self.password, secret=self.enabled_pwd, global_delay_factor=3) as device: device.enable() output = device.send_command(cmd) cdp_neighbors = parse_output("cisco_ios", cmd, output) return cdp_neighbors except Exception as err: self.print_connection_err(err, hostname)
def cisco_commands(a_device, output_q): """ Use Netmiko to execute commands. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_device) hostname = remote_conn.base_prompt ## Runs the show interface status command on the connected device sh_commands = remote_conn.send_command("sh int status") ## Parses the output of the command into a dictionary so it can be worked with easier sh_commands_parsed = parse_output(platform="cisco_ios", command="sh int status", data=sh_commands) print("") print(hostname) print("") ## Opens/creates the modified_interfaces.csv file and tells it to append lines using the 'a' argument with open('modified_interfaces.csv', 'a') as file: ## Loops through the parsed output of show interface status for i in sh_commands_parsed: ## if the vlan is in the user_vlans list and the status is either connected or notconnect ## then the ports shall be recorded in the csv and then shutdown if (i['vlan'] in user_vlans) and (i['status'] == 'connected' or i['status'] == 'notconnect'): intf = (i['port']) vlans = (i['vlan']) status = (i['status']) csv_var = hostname + ',' + intf file.write(csv_var + '\n') print('Found port ' + intf, 'on VLAN ' + vlans, "\n" 'Current Port status is: ' + status, "\n" 'Port will be shutdown') print("") config_commands = ['interface ' + intf, 'shutdown'] remote_conn.send_config_set(config_commands) output_q.put(output_dict)
def run_cmd(ip, dev_type, username, password, command): # create connection connection = netmiko.ConnectHandler( ip=ip, device_type=dev_type, username=username, password=password, ) # run the first command to get the interfaces on the current node result = connection.send_command(command) # use ntc_templates to parse the output into json parsed_result = parse_output(platform=dev_type, command=command, data=result) # beutify the json file and print parsed_result = json.dumps(parsed_result, indent=2) connection.disconnect() return parsed_result
def l3data_ios(core, l3dict, user, pas): for device in core["ios"]: conn = ConnectHandler(device_type="cisco_ios_ssh", host=device, username=user, password=pas) print(f"Extrayendo data l3 --> {conn.find_prompt()}") arp = parse_output(platform="cisco_ios", command="show ip arp", data=conn.send_command(f"show ip arp")) for entry in arp: if entry["interface"] not in l3dict["ios"].keys(): l3dict["ios"][entry["address"]] = {} l3dict["ios"][entry["address"]]["l3inter"] = entry["interface"] l3dict["ios"][entry["address"]]["mac"] = entry["mac"] elif entry["interface"] in l3dict["ios"].keys(): pass conn.disconnect()
def cisco_commands(a_device, output_q, desc, intf, vlan): """ Use Netmiko to execute commands. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_device) hostname = remote_conn.base_prompt ## commands to be ran on device config_commands = ([ 'interface ' + intf, 'switchport access vlan ' + vlan, 'description ' + desc ]) ## runs the show interface status command on the device sh_commands = remote_conn.send_command("sh int " + intf + " status") ## uses ntc_template to parse the command output into a dictionary which can be easily worked with sh_commands_parsed = parse_output(platform="cisco_ios", command="sh int status", data=sh_commands) ## loop through the parsed output for i in sh_commands_parsed: ## checks if the vlan is in the allowed_lists list & runs config_commands if it is if i['vlan'] in allowed_vlans: remote_conn.send_config_set(config_commands) print("=" * 60 + "\n") print(hostname + ' ' + intf) print("") print(config_commands) print("=" * 60 + "\n") else: ## otherwise it will print the below message and show the port config so it can be understood why it failed print("=" * 60 + "\n") print(hostname + ' ' + intf) print("") print( "VLAN not allowed or switchport is trunk. \nCurrent port configuration: " + i['vlan']) print("=" * 60 + "\n") output_q.put(output_dict)
def CollIPRIB(): #登录设备,查看路由表,并处理。只留下/24的路由。 WL3750 = { 'device_type': 'cisco_ios', 'host': '1.1.1.1', 'username': '******', 'password': '******' } SWssh = ConnectHandler(**WL3750) IPrib = SWssh.send_command("show ip route") #用NTC templates处理一下获得的数据 RibInfo = parse_output(platform='cisco_ios', command="show ip route", data=IPrib) TmpList = [] for i in RibInfo: if i['mask'] == '24': TmpStr = i['network'] + '/' + i['mask'] TmpList.append(TmpStr) else: continue #用Set给列表去重,防止有多个下一跳ECMP的情况,再转回列表返回。 return list(set(TmpList))
def build_parsed_data_from_output(filepath, test_dir=TEST_DIR): """ Generates a YAML file from the file containing the command output. The command output should be stored in a file in the appropriate directory; for example, ``tests/cisco_ios/show_version/cisco_ios_show_version.raw`` This uses ``lib.ntc_templates.parse.parse_output``, so the template must be in the ``templates/`` directory, and ``templates/index`` must be updated with the correct entry for the template. Args: filepath (str): The path to the file containing sample command output. test_dir (str): The root directory to story the resulting YAML file. Returns None: File I/O is performed to generate a YAML file pased on command output. Example: >>> root_dir = "tests/cisco_ios/show_version" >>> os.listdir(root_dir) ['cisco_ios_show_version.raw'] >>> filepath = "tests/cisco_ios/show_version/cisco_ios_show_version.raw" >>> build_parsed_data_from_output(filepath) >>> os.listdir(root_dir) ['cisco_ios_show_version.raw', 'cisco_ios_show_version.yml'] >>> """ platform, command, filename = parse_test_filepath(filepath) with open(filepath, encoding="utf-8") as output_file: output_data = output_file.read() structured_data = parse_output(platform, command, output_data) command_with_underscores = command.replace(" ", "_") yaml_file = "{0}/{1}/{2}/{3}.yml".format(test_dir, platform, command_with_underscores, filename) ensure_yaml_standards({"parsed_sample": structured_data}, yaml_file)
def main(): print('=== main ===') device = { 'hostname': 'myComputer', 'ip': '***.***.***.***', 'username': '******', 'password': '******', 'secret': '***', 'login_id_text': 'login:'******'login_pw_text': 'Password:'******'enable_pw_text': 'Password:'******'ifconfig') #print(result) parsed = parse_output(platform="ubuntu", command="ifconfig", data=result.decode()) pprint(parsed) tn.close() print('=== main end ===')
def show_platform(): node_list = [] for host_ in host_list: try: host = host_.split()[0] print('Connecting to ' + host + '...') tnt_session = ConnectHandler( device_type="cisco_xr", host=host, username="******", password="******", ) plat = tnt_session.send_command("show platform", use_textfsm=True) tnt_session.disconnect() print('Disconnected ' + host + '...') plat_parsed = parse_output(platform="cisco_xr", command="show version", data=plat) new_list = [host, plat_parsed] node_list.append(new_list) except: print('Node ' + host.split()[0] + ' is unreachable') return None return node_list
def ios_connection(host, device_type, command): ios_device = { 'device_type': device_type, 'host': host, 'username': ios_info['username'], 'password': ios_info['password'], 'secret': ios_info['secret'] } try: net_connect = ConnectHandler(**ios_device) net_connect.enable() output = net_connect.send_command(command) info = parse_output(platform=device_type, command=command, data=output) net_connect.disconnect() except ValueError: reason = e raise ValueError( f"SCOTT Failed to execute cli on {host} due to {reason}") if not net_connect: net_connect.disconnect() return (info)