def proxy_vsr(): vsr_host = { "host": vsr, # Far-end vSR behind JumpServer "username": "******", # Username to the vSR should never change. "password": "******", # Password to the vSR should never change. "device_type": "alcatel_sros", "ssh_config_file": "~/.ssh/config", # location of the ssh config on the local machine running this script, in order to use jumpserver as proxy. } net_connect = Netmiko(**vsr_host) # Display the Chassis type to screen. system_type = net_connect.send_command( 'show system information | match "System Type"') execute = f"Executing Commands on vSR: {system_type} Using the file: {ftp_file}" print(execute) syntax = net_connect.send_command('exec -syntax ' + 'ftp://*****:*****@' + JumpServer + '/pub/vzw/' + ftp_file) if 'Verified' in syntax: print("Syntax Check Verified. Executing configuration.") else: print(syntax) syntax = net_connect.send_command('exec ' + 'ftp://*****:*****@' + JumpServer + '/pub/vzw/' + ftp_file, expect_string=r'#') if 'failed' in syntax: print(":: Failed ::: " + syntax) else: print(syntax) net_connect.disconnect()
def main(): timestamp = datetime.now().strftime('%Y%m%d%H%M%S') # Get input from user while True: try: subnets = input( "Enter a subnet(s) (CIDR notation, space delimited): ").split( ) for i in range(0, len(subnets)): subnets[i] = ipaddress.IPv4Network(subnets[i]) except: if input( "Invalid data entered. Press any key to continue or 'q' to quit. " ) == 'q': exit() else: break if len(subnets) > 0: # gather username and password cisco_user = input("Device Username: "******"Device Password: "******"Please wait while inventory report is being generated") # Open csv file for write operation with open(f'{os.getcwd()}/discovered_switches_{timestamp}.csv', 'w') as csv_file: report_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) report_writer.writerow(['Hostname', 'IP Address', 'Model']) for subnet in subnets: for ip in subnet.hosts(): # Create connection object for Netmiko conn = { "host": str(ip), "username": cisco_user, "password": cisco_pass, "device_type": "cisco_ios", } # Attempt connection try: net_connect = Netmiko(**conn) vers = net_connect.send_command('show version') except: print(f"Error connecting to {str(ip)}") else: hostname = net_connect.find_prompt().split('#')[0] model = net_connect.send_command( 'show inventory | inc PID').splitlines()[0].split( ',')[0].lstrip('PID:').strip() report_writer.writerow([hostname, str(ip), model]) net_connect.disconnect() print(f"Completed successfully on {str(ip)}")
class NetmikoDevice(Device): def connect(self): print(f"\n\n----- Connecting to {self.hostname}:{self.port}") self.connection = Netmiko( self.hostname, port=self.port, username=self.username, password=self.password, device_type=self.device_type, ) print(f"----- Connected! --------------------") return True def get_facts(self): show_hostname_output = self.connection.send_command("show hostname") show_version_output = self.connection.send_command("show version") show_serial_output = self.connection.send_command( "show license host-id") show_uptime_output = self.connection.send_command("show system uptime") facts = dict() facts["os_version"] = get_version_from_show(show_version_output) facts["hostname"] = show_hostname_output.strip() facts["serial_number"] = show_serial_output.strip()[ 20:] # Don't do this :-) facts["uptime"] = get_uptime_from_show(show_uptime_output) return facts def disconnect(self): self.connection.disconnect() print(f"----- Disconnected! --------------------") return True
def run_cmds(host, username, password, cmds): homedir = os.path.dirname(os.path.realpath(__file__)) print(host, username, password) net_connect = Netmiko(host=host, username=username, password=password, device_type="cisco_ios", timeout=30) hostname = net_connect.find_prompt() hostname = re.sub('#', '', hostname) net_connect.send_command("term len 0") for cmd in cmds: print("\t", cmd) try: cmd_output = net_connect.send_command(cmd, hostname) net_connect.read_until_prompt_or_pattern() timestr = time.strftime("%Y%m%d-%H%M%S") filename = os.path.join(homedir, hostname + "_OUTPUT_" + timestr + ".txt") cmd_output = cmd_output.strip() if cmd_output != "": print(cmd_output.strip()) """ if 'hostname' in cmd_output: text_file = open(filename, "w") text_file.write(cmd_output) text_file.close() print(" output file saved as:", filename) else: print(" output file was NOT saved for:", host) """ except Exception as e: print("ERROR EXECUTING", cmd, "on host: ", host) print(e)
def main(): my_device = { 'host': 'ios-xe-mgmt.cisco.com', 'username': '******', 'password': '******', 'device_type': 'cisco_ios', 'port': 8181 } net_connect = Netmiko(**my_device) routes = net_connect.send_command('sh ip route', use_textfsm=True) neigbors = net_connect.send_command('sh cdp neighbor', use_textfsm=True) arp_entries = net_connect.send_command('sh ip arp', use_textfsm=True) print("ROUTES : \n") for route in routes: print(route) print("NEIGHBORS : \n") if type(neigbors) == list: for nei in neigbors: print(nei) print("ARPs : \n") for arp in arp_entries: print(arp) net_connect.disconnect()
def Validate_ccm(self): for node in self.data["site_list"]: mep_name = 100000 + self.data['item'] if 'EP' in node['side']: if node['login']['device_type'] == 'accedian': net_connect = Netmiko(**node['login']) print(node['Node_name'], end=' : ') output = net_connect.send_command( "cfm show mep status LEXXX-{}|{}|{}".format( mep_name, self.data['MEG_level'], node['Remote_MEP'])) if len(re.findall("Inactive", output)) == 14: print("ccm is UP") else: print("CCm did not came Up") net_connect.disconnect() else: net_connect = Netmiko(**node['login']) print(node['Node_name'], end=' : ') output = net_connect.send_command( "show ethernet cfm services domain COLT-{} service ALX_NCS_LE-{}" .format(self.data['MEG_level'], mep_name)) if len(re.findall("all operational, no errors", output)) == 2: print("ccm is UP") else: print("CCm did not came Up") net_connect.disconnect()
def command_cisco(self, hosts, set_command): ''' :param hosts: hostname or IP of the device :param set_command: command send to device, can be string or list :return: ''' device = { 'ip': hosts, 'username': self.username, 'password': self.password, 'use_keys': self.keys, 'device_type': 'cisco_ios', } try: net_connect = Netmiko(**device, fast_cli=True) if isinstance(set_command, list): result = [] for command in set_command: result.append(net_connect.send_command(command)) return result else: return net_connect.send_command(set_command) except paramiko.ssh_exception.AuthenticationException: print("\nWrong Password\n")
def main(): # generate input_file from input_subnets containing all IPs to perform inventory scan against while True: try: input_ips = input( "Enter a space delimited list of IPs to scan: ").split() for i in range(0, len(input_ips)): input_ips[i] = ipaddress.IPv4Address(input_ips[i]) except: if input( "Invalid data entered. Press any key to continue or 'q' to quit. " ) == 'q': exit() else: break if len(input_ips) > 0: # gather username and password cisco_user = input("Device Username: "******"Device Password: "******"Please wait while inventory report is being generated") sys.stdout.flush() for ip in input_ips: # Create connection object for Netmiko conn = { "host": str(ip), "username": cisco_user, "password": cisco_pass, "device_type": "cisco_ios", } # Attempt connection try: net_connect = Netmiko(**conn) vers = net_connect.send_command('show version') except: print(f"Error connecting to {str(ip)}") else: # Special handling for Nexus if "Nexus" in vers: ports = net_connect.send_command( 'show int bri | inc "Administratively"') # Normal handling for IOS else: ports = net_connect.send_command( 'show ip int bri | inc administratively') for line in ports.splitlines(): int = line.split()[0] if int.startswith('Gig'): net_connect.send_config_set( [f'interface {int}', f'no shutdown']) net_connect.save_config() net_connect.disconnect()
def get_prompt(dev): H = [ key for (key, value) in output1.items() if value['host'] == dev['host'] ][0] print("Fetching information from %s..." % H) net_conn = Netmiko(**dev) if dev['device_type'] == 'cisco_ios': output = net_conn.send_command("show mac address-table", use_textfsm=True) # counting the number of ports in the mac address table C2 = Counter(x['destination_port'] for x in output) C3 = dict(C2) # returning key values for >3 ports C3_switch = [key for (key, value) in C3.items() if value >= 3] print("Writing information from %s to file.." % H) # writing the output to a csv file with open('Potential_switch_ports.csv', 'a') as f: fieldnames = ['Device Name', 'Port Number'] writer = csv.DictWriter(f, fieldnames=fieldnames, restval='') writer.writeheader() for i in range(len(C3_switch)): writer.writerow({ 'Device Name': H, 'Port Number': C3_switch[i] }) elif dev['device_type'] == 'hp_procurve': output = net_conn.send_command("show mac-address", use_textfsm=True) C2 = Counter(x['port'] for x in output) C3 = dict(C2) C3_switch = [key for (key, value) in C3.items() if value >= 3] print("Writing information from %s to file.." % H) with open('Potential_switch_ports.csv', 'a') as f: fieldnames = ['Device Name', 'Port Number'] writer = csv.DictWriter(f, fieldnames=fieldnames, restval='') writer.writeheader() for i in range(len(C3_switch)): writer.writerow({ 'Device Name': H, 'Port Number': C3_switch[i] }) elif dev['device_type'] == 'dell_os6': output = net_conn.send_command("show mac address-table", use_textfsm=True) C2 = Counter(x['port'] for x in output) C3 = dict(C2) C3_switch = [key for (key, value) in C3.items() if value >= 3] print("Writing information from %s to file.." % H) with open('Potential_switch_ports.csv', 'a') as f: fieldnames = ['Device Name', 'Port Number'] writer = csv.DictWriter(f, fieldnames=fieldnames, restval='') writer.writeheader() for i in range(len(C3_switch)): writer.writerow({ 'Device Name': H, 'Port Number': C3_switch[i] })
def main(): while True: try: dev_ips = input("Destination IP or IPs (space delimited): ").split() for i in range(0, len(dev_ips)): dev_ips[i] = ipaddress.IPv4Address(dev_ips[i]) add_ips = input("SNMP Manager IP(s) to add (space delimited): ").split() for i in range(0, len(add_ips)): add_ips[i] = ipaddress.IPv4Address(add_ips[i]) #rem_ips = input("SNMP Manager IP(s) to remove (space delimited): ").split() #for i in range(0, len(rem_ips)): #rem_ips[i] = ipaddress.IPv4Address(rem_ips[i]) except: if input("Invalid data entered. Press any key to continue or 'q' to quit. ") == 'q': exit() else: break if len(add_ips) > 0 or len(rem_ips) > 0: # gather username and password cisco_user = input("username: "******"Please wait while the update is being performed") # Create Connection object for Netmiko for ip in dev_ips: conn = { "host": str(ip).rstrip("\n"), "username": cisco_user, "password": cisco_pass, "device_type": "cisco_ios", } # Attempt the connection try: net_connect = Netmiko(**conn) vers = net_connect.send_command('show version') except: print(f"Connection to {ip} failed") else: hostname = net_connect.find_prompt().split('#')[0] # Special handling for Nexus if "Nexus" in vers: #add handling for nexus switches here pass acl = net_connect.send_command('show running-config | inc snmp-server community bstar') if acl == "": acl = net_connect.send_command('show running-config | inc snmp-server community GIpublicD') #for i in rem_ips: #net_connect.send_config_set(['interface vlan '+vlan, rem_comm+str(i)]) for i in add_ips: net_connect.send_config_set([f"access-list {acl.split()[-1]} permit {i}"]) # Save config and disconnect session net_connect.save_config() net_connect.disconnect() print(f"Successfully updated SNMP ACL on {hostname}")
def command_ouput(self, interface_name_list, device_list): print("**** statistic of traffic on both devices") for uni_port, device in zip(interface_name_list, device_list): net_connect = Netmiko(**device) command = 'show policy-map interface {}.{} | utility egrep "Match\|input\|output\|Drop"'.format( uni_port, self.sub_interface) command_ouput = net_connect.send_command("show run hostname") command_ouput += net_connect.send_command(command) print(command_ouput) net_connect.disconnect()
def do_connect(self, device, cmd): output = results[0]["dmca"]["device"] error = results[0]["dmca"]["error"] did_connect = False try: net_connect = Netmiko(**device, banner_timeout=10) did_connect = True except Exception as e: error.append(e) return if did_connect: device_name = device['host'] config_output = net_connect.send_config_set(cmd) if self.choice == "a": if "MAC filter already exists" in config_output: output.append([ device_name, self.mac + " already exists in controller!" ]) else: show_output = net_connect.send_command( 'show exclusionlist') sleep(1) if self.mac in show_output: output.append( [device_name, self.mac + " successfully added!"]) else: # If all goes wrong - print log output.append([device_name, config_output]) else: if "does not exist" in config_output: output.append([ device_name, self.mac + " does not exist in controller!" ]) else: show_output = net_connect.send_command( 'show exclusionlist') sleep(1) if self.mac not in show_output: output.append( [device_name, self.mac + " successfully removed!"]) else: # If all goes wrong - print log output.append([device_name, config_output]) net_connect.disconnect() return
class Asa(): def __init__(self, asa_user, asa_pass): self.asa_user = asa_user self.asa_pass = asa_pass self.net_conn = Netmiko(host=dc1_asa, username=asa_user, password=asa_pass, device_type='cisco_asa') def get_asa_pfxs(self): asa_ex_online, asa_ex_protect = ([] for i in range(2)) # Gathers the object-groups for exchange-online and protection from the ASA asa_ex_online1 = self.net_conn.send_command( 'show run object-group id Exchange-online-v1') asa_ex_protect1 = self.net_conn.send_command( 'show run object-group id Exchange-online-protection-v1') self.net_conn.disconnect() # Strip so just have network and subnet mask for x in asa_ex_online1.splitlines(): if 'network-object' in x: asa_ex_online.append((x.replace(' network-object ', ''))) for x in asa_ex_protect1.splitlines(): if 'network-object' in x: asa_ex_protect.append((x.replace(' network-object ', ''))) # Swap any host entries for 255.255.255.255 for x in asa_ex_online: if 'host' in x: asa_ex_online.remove(x) asa_ex_online.append(x.split('host ')[1] + ' 255.255.255.255') for x in asa_ex_protect: if 'host' in x: asa_ex_protect.remove(x) asa_ex_protect.append(x.split('host ')[1] + ' 255.255.255.255') return [asa_ex_online, asa_ex_protect] # Applies the configuration to the ASAs def post_asa_pfxs(self): print("Applying configuration on {}, please wait...".format(dc1_asa)) show_cmds = [ 'show run object-group id Exchange-online-v1', 'show run object-group id Exchange-online-protection-v1' ] asa_log = [] asa_before = self.net_conn.send_config_set(show_cmds) asa_log.append(self.net_conn.send_config_set(asa_config)) asa_log.append(self.net_conn.save_config()) asa_after = self.net_conn.send_config_set(show_cmds) self.net_conn.disconnect() return [asa_before[13:-33], asa_after[13:-33], asa_log]
def mpls_metrics(a_device): ''' Examine 'show router mpls interface results - Extract Interface Name/TE-Metric with regex / NTC-Templates. ''' global dict_mplsInt, dict_IsisInt try: net_connect = Netmiko(host=a_device, username=username, password=password, device_type='alcatel_sros') # Home Sandbox # net_connect = Netmiko(host='192.168.253.136', username=username,password=password, device_type='alcatel_sros') # Work Sandbox mplsInt = net_connect.send_command("show router mpls interface", use_textfsm=True) sortedListMpls = sorted(mplsInt, key=itemgetter('port')) for dict_mplsInt in sortedListMpls: n = SimpleNamespace(**dict_mplsInt) cmd = "/configure router isis interface " + n.interface + " level 2 metric " + n.te_metric net_connect.send_command( cmd ) # Update the IS-IS Metrics with the extraced TE-Metric value. mpls_pre_int = n.interface mpls_pre_metric = n.te_metric # except Exception as e: # print ("There was an error", e) # def isis_interface(a_device): # try: time.sleep(2) # Ensure the ISIS interface has been configured. # net_connect = Netmiko(host=a_device, username=username,password=password, device_type='alcatel_sros') # Home Sandbox sysname = net_connect.send_command( 'show system information | match Name') isisInt = net_connect.send_command("show router isis interface", use_textfsm=True) sortedListIsis = sorted(isisInt, key=itemgetter('interface')) print(sysname) for dict_IsisInt in sortedListIsis: print('Updated ISIS Interface: ' + dict_IsisInt["interface"] + " with new metrics: " + dict_IsisInt["l2_metric"]) if dict_IsisInt["l2_metric"] != mpls_pre_metric: print("ISIS Metric: " + (dict_IsisInt["l2_metric"] + " on interface: " + (dict_IsisInt["interface"]) + " Mismatch to MPLS Metric: " + (mpls_pre_metric))) except Exception as er: print("Error Encountered: ", er)
def ssh_get_mac(device_type): global inventory global mac_table_all table_header = [ 'DESTINATION_ADDRESS', 'TYPE', 'VLAN', 'DESTINATION_PORT', 'HOSTNAME' ] homedir = os.path.dirname(os.path.realpath(__file__)) homedir = os.path.join(homedir, 'mac') if not os.path.exists(homedir): os.makedirs(homedir) for device in inventory[device_type]: table = [] host = device['host'] username = device['username'] password = device['password'] try: print("Retrieving MAC table for:", host) net_connect = Netmiko(host=host, username=username, password=password, device_type=device_type, timeout=10) hostname = net_connect.find_prompt() hostname = re.sub('#', '', hostname) net_connect.send_command("term len 0", use_textfsm=False) cmd_output = net_connect.send_command("show mac address-table", use_textfsm=False) re_table = textfsm.TextFSM(io.StringIO(fsm[device_type]['mac'])) cmd_output = re_table.ParseText(cmd_output) if "ailed" not in cmd_output: print(" Success!: ", cmd_output[0], "more...") for mac_entry in cmd_output: mac_entry.append(hostname) table.append(mac_entry) table = sorted(table, key=None, reverse=False) filename = os.path.join( homedir, hostname + "_mac_" + time.strftime("%Y%m%d-%H%M%S") + ".csv") write_csv(table_header, table, filename) else: print(" Failed!:\n", cmd_output) except Exception as e: print(e) mac_table_all = mac_table_all + table filename = os.path.join( homedir, "all_mac_" + time.strftime("%Y%m%d-%H%M%S") + ".csv") mac_table_all = sorted(mac_table_all, key=None, reverse=False) write_csv(table_header, mac_table_all, filename)
def netmiko_Set_config(item1, inter_exter): if inter_exter == 'internal': net_connect = Netmiko(**deviceB) print('***** log in to device {}'.format(deviceB['host'])) else: net_connect = Netmiko(**deviceA) print('***** log in to device {}'.format(deviceA['host'])) f = open( file_path + "/commands/" + str(item1) + "_Loop_" + str(inter_exter) + "_Set_command.txt", 'r') f2 = f.readlines() clear_QOS_ouput() output = net_connect.send_config_set(f2) net_connect.commit() net_connect.exit_config_mode() print(output) command = "show ethernet loopback active | include ID" show_output = net_connect.send_command(command) if item1 == "L2": loop_id_to_render = get_L2_loop_ID(show_output) if loop_id_to_render != "1": print("**** doing rendering one more time") Command_Creation(location, item1, item2, inter_exter, loop_id_to_render, **interface_name) net_connect.disconnect()
def send_cmd(device, cmd_list): net_connect = Netmiko(**device) response = {} for command in cmd_list: response[command] = net_connect.send_command(command) net_connect.disconnect() return response
def show_to_txt(namepass,command): b = len(namepass) d = len(command) newfile = ('./'+date) os.mkdir(newfile) os.chdir(newfile) for j in range(1,b): print('Now is checking '+namepass[j][1]+',the ip address is '+namepass[j][2]) my_device = { "host": namepass[j][2], "username": namepass[j][4], "password": namepass[j][5], "device_type": "cisco_ios", } net_connect = Netmiko(**my_device) write_file = open(namepass[j][1]+'_'+date+'.txt', 'w') #模式为追加 for n in range(0,d): print(command[n][1], file=write_file) print("\n", file=write_file) output = net_connect.send_command(command[n][1]) print(output, file=write_file) print("\n=============================================\n", file=write_file) write_file.close() net_connect.disconnect() os.chdir('..')
def function_capture(data_path): book = xlrd.open_workbook(data_path) first_sheet = book.sheet_by_index(0) cell = first_sheet.cell(0, 0) for i in range(first_sheet.nrows): my_device = { "host": first_sheet.row_values(i)[0], "username": first_sheet.row_values(i)[1], "password": first_sheet.row_values(i)[2], "device_type": first_sheet.row_values(i)[3], } print('Device Executed') print(my_device["host"]) try: net_connect = Netmiko(**my_device) output = net_connect.send_command("show run") print(output) write = open(first_sheet.row_values(i)[0] + '.txt', 'w') write.write(output) net_connect.disconnect() except: pass
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 main(): my_device = { 'host': 'ios-xe-mgmt.cisco.com', 'username': '******', 'password': '', 'device_type': 'cisco_ios', 'port': 8181 } net_connect = Netmiko(**my_device) # commands = ['int gi3', 'ip addr 1.2.3.4 255.255.255.0'] # # output = net_connect.send_config_set(commands) # print(output) # # output = net_connect.send_command('sh run int gi3') # print(output) # output = net_connect.send_config_from_file('commands_file') print(output) output = net_connect.send_command('sh run int gi3') print(output) net_connect.disconnect()
def conn_link_tests(data): results = dict() for host, mgmt_ip in data.items(): host_response = {} # creating netmiko connector net_connect = Netmiko( mgmt_ip, username="******", password=pwd, device_type="cisco_ios", ) loc = "../inventory/host_vars/" + host + ".yml" parsed_host_data = doc_read(loc) # rurnning the test: for interface in parsed_host_data["interfaces"]: if interface["interface"] != "loopback0": target = str(get_peer_ip(IPNetwork(interface["ip"]))) host_response.update({ interface["interface"]: net_connect.send_command(f"ping {target}") }) time.sleep(2) # testing with names, netmiko test will be from netautomator # host_response.update({interface["interface"]:target}) results.update({host: host_response}) return results
def status_check(ips): try: cisco_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**cisco_IOS) net_connect.enable() with open('status_check.txt') as command: output = '' for commands in command: output += "=====>" + commands + net_connect.send_command( commands) + '\n' net_connect.disconnect() return "-----> Working on host " + ips + " <-----" "\n" + output + "\n" except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authentication failed for " + ips)
def main(): """ Execution starts here. """ # Read the hosts file into structured data, may raise YAMLError with open("hosts.yml", "r") as handle: host_root = safe_load(handle) # Iterate over the list of hosts (list of dictionaries) for host in host_root["production"]: # Load the host-specific VRF declarative state # with open(f"vars/commands_{host}.yml", "r") as handle: with open(f"vars/commands_{host['role']}.yml", "r") as handle: commands = safe_load(handle) # Create netmiko SSH connection handler to access the device conn = Netmiko( host=host["name"], username="******", password="******", device_type="cisco_ios", ) print(f"\nLogged into {conn.find_prompt()} successfully") # Iterate over list of commands, issue each one, and print # the results for command in commands["commands"]: result = conn.send_command(command) print(f"\n{command}\n{'-' * len(command)}") print(result) conn.disconnect()
def parse_accedian(self): for node in self.data["site_list"]: if node['login']['device_type'] == 'cisco_xr': pass else: net_connect = Netmiko(**node['login']) node['index'] = {} if node['Protected'] == 'YES': node['out_port'] = 'LAG-{}'.format(node['Nni_port'] // 2 + 1) else: node['out_port'] = 'PORT-{}'.format(node['Nni_port']) for mep_meg_dmm_slm in mep_meg_dmm_slm_list: output = net_connect.send_command('cfm show {} configuration'.format(mep_meg_dmm_slm)) template = open('ntc/accedian_show_{}_index.textfsm'.format(mep_meg_dmm_slm)) re_table = textfsm.TextFSM(template) fsm_results = re_table.ParseText(output) if mep_meg_dmm_slm == 'meg': node['index']['del_meg'] = 1 for rows in fsm_results: if rows[1] == 'LEXXX-{}'.format(100000 + self.data['item']): node['index']['del_meg'] = rows[0] if len(fsm_results) == 0: node['index'][mep_meg_dmm_slm] = 1 else: node['index'][mep_meg_dmm_slm] = int(fsm_results[-1][0]) + 1 net_connect.disconnect() print("**** persing completed on {}".format(node['Node_name'])) return node['index']
def backup(ips): try: cisco_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**cisco_IOS) net_connect.enable() out = net_connect.send_command("show running-config") net_connect.disconnect() with open(path + '/' + ips + '.txt', 'w') as fileouts: fileouts.write(out) except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authenticaftion failed for " + ips)
def showint(): array = [] command = [] array = read_excel('Zhu_list.xlsx', 0) command = read_excel('Zhu_list.xlsx', 1) b = len(array) d = len(command) for j in range(1,b): print('Now is checking'+array[j][1]+',the ip address is '+array[j][2]) my_device = { "host": array[j][2], "username": array[j][4], "password": array[j][5], "device_type": "cisco_ios", } net_connect = Netmiko(**my_device) write_file = open(array[j][1]+'_'+date+'.txt', 'w') #模式为追加 for n in range(0,d): output = net_connect.send_command(command[n][1]) #print(output) print(output, file=write_file) print("\n=============================================\n", file=write_file) write_file.close() net_connect.disconnect()
def backupH(ips): try: hirschmann_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**hirschmann_IOS) net_connect.enable() out = net_connect.send_command( "copy config running-config remote tftp://" + tftp_ip + "/OSC." + ips + ".xml") net_connect.disconnect() except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authenticaftion failed for " + ips)
def ssh_command2(j, cmd="show version"): print("#" * 80) net_conn = Netmiko(**j) output = net_conn.send_command(cmd) net_conn.disconnect() print("#" * 80) return output
def get_output(device_id, send_command): '''This function connect to a device run a command and return the output ''' net_conn = Netmiko(**device_id) output = net_conn.send_command(send_command) return output
#!/usr/bin/env python from __future__ import print_function, unicode_literals # Netmiko is the same as ConnectHandler from netmiko import Netmiko from getpass import getpass my_device = { 'host': "host.domain.com", 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', # Increase (essentially) all sleeps by a factor of 2 'global_delay_factor': 2, } net_connect = Netmiko(**my_device) # Increase the sleeps for just send_command by a factor of 2 output = net_connect.send_command("show ip int brief", delay_factor=2) print(output) net_connect.disconnect()
#!/usr/bin/env python from __future__ import print_function, unicode_literals # Netmiko is the same as ConnectHandler from netmiko import Netmiko from getpass import getpass my_device = { 'host': 'host.domain.com', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', } net_connect = Netmiko(**my_device) output = net_connect.send_command("show ip int brief") print(output) net_connect.disconnect()
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass nxos1 = { "host": "nxos1.twb-tech.com", "username": "******", "password": getpass(), "device_type": "cisco_nxos", } commands = ["logging history size 500"] net_connect = Netmiko(**nxos1) print() print(net_connect.find_prompt()) output = net_connect.send_config_set(commands) output += net_connect.send_command("copy run start") print(output) print()
except NameError: host = input("Enter host to connect to: ") password = getpass() device = { 'host': host, 'username': '******', 'password': password, 'device_type': 'cisco_ios', } net_connect = Netmiko(**device) # Use send_config_set() to make config change config = ['logging console', 'logging buffer 15000'] output = net_connect.send_config_set(config) output_printer(output) # Use send_config_from_file() to make config change output = net_connect.send_config_from_file('config.txt') output_printer(output) message = "Verifying config change\n" output = net_connect.send_command("show run | inc logging") if '8000' in output: message += "Logging buffer is size 8000" else: message += "Logging buffer size is not correct!" output_printer(message)
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass key_file = "/home/gituser/.ssh/test_rsa" cisco1 = { "device_type": "cisco_ios", "host": "cisco1.twb-tech.com", "username": "******", "use_keys": True, "key_file": key_file, } net_connect = Netmiko(**cisco1) print(net_connect.find_prompt()) output = net_connect.send_command("show ip arp") print(output)
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass cisco1 = { 'host': 'cisco1.twb-tech.com', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', } net_connect = Netmiko(**cisco1) command = 'copy flash:c880data-universalk9-mz.154-2.T1.bin flash:test1.bin' print() print(net_connect.find_prompt()) output = net_connect.send_command(command, delay_factor=4) print(output) print()
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass cisco1 = { "host": "cisco1.twb-tech.com", "username": "******", "password": getpass(), "device_type": "cisco_ios", } net_connect = Netmiko(**cisco1) command = "show ip int brief" print() print(net_connect.find_prompt()) output = net_connect.send_command(command) net_connect.disconnect() print(output) print()
R01 = { "host": "192.168.1.32", "username": "******", "password": getpass(), "device_type": "cisco_ios", } cfg_file = "config_changes.txt" net_connect = Netmiko(**R01) # routing table before change # command = "show ip route" print('routes PRE changes') print(net_connect.find_prompt()) pre_routes = net_connect.send_command(command) print(pre_routes) print() # make changes # print() print(net_connect.find_prompt()) output = net_connect.send_config_from_file(cfg_file) print(output) print() # routing table after changes # print('routes POST changes') print(net_connect.find_prompt()) post_routes = net_connect.send_command(command) print(post_routes)
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass cisco1 = { "host": "cisco1.twb-tech.com", "username": "******", "password": getpass(), "device_type": "cisco_ios", } net_connect = Netmiko(**cisco1) command = "show ip int brief" print() print(net_connect.find_prompt()) output = net_connect.send_command(command, use_textfsm=True) net_connect.disconnect() print(output) print()
#!/usr/bin/env python from __future__ import print_function, unicode_literals # Netmiko is the same as ConnectHandler from netmiko import Netmiko from getpass import getpass my_device = { 'host': 'host.domain.com', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', } net_connect = Netmiko(**my_device) # Requires ntc-templates to be installed in ~/ntc-templates/templates output = net_connect.send_command("show ip int brief", use_textfsm=True) print(output)