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 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 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 ciscoasacon(ipaddr, username, password, secret, networknodetype): if secret == "none": CiscoASAConnectNoEnable = { "host": ipaddr, "username": username, "password": password, "device_type": networknodetype} net_connect = Netmiko(**CiscoASAConnectNoEnable) # This is where it connect with SSH for no enable/secret elif secret != "none": CiscoASAConnectWithEnable = { "host": ipaddr, "username": username, "secret": secret, "password": password, "device_type": networknodetype} net_connect = Netmiko(**CiscoASAConnectWithEnable) # This is where it connect with SSH print("\n") print(net_connect.find_prompt()) print(net_connect.enable()) print(net_connect.send_command("sh clock")) clock = net_connect.send_command("sh clock") print(net_connect.send_command("sh int ip brief")) interfaces = net_connect.send_command("sh int ip brief") shrun = net_connect.send_command("sh run") print(net_connect.send_command("sh run")) net_connect.disconnect() writetohdd(interfaces, shrun)
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 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 send_config_command(device, config_commands): net_connect = Netmiko(**device) net_connect.find_prompt() net_connect.config_mode(config_command='configure private') if net_connect.check_config_mode(): for c in config_commands: output = net_connect.send_config_set(c, exit_config_mode=False) if 'syntax error' in output: print('''Command "{}" error! {} '''.format(c, output)[:-23]) if exit_or_continue(): break elif 'missing argument' in output: print('''Command "{}" error! {} '''.format(c, output)[:-23]) if exit_or_continue(): break elif 'invalid interface type in' in output: print('''Command "{}" error! {} '''.format(c, output)[:-23]) if exit_or_continue(): break net_connect.send_config_set("show | compare", exit_config_mode=False) net_connect.commit(and_quit=True) 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 envoi(): start = time.time() #On parcourt le fichier de conf pour lire les commandes à envoyer et le fichier send.list pour l'IP ou les IPs où diffuser la conf with open('conf') as f: lines = f.read().splitlines() with open('send.list') as f: ip = f.read().splitlines() for ip in ip: print("Envoi de la configuration sur l'adresse : "+ ip) #Définition de l'equipment utilisé pour la connexion netmiko via un dictionnaire qui stocke les variables nécessaires pour netmiko equipment = { 'device_type': 'cisco_ios', 'ip': ip, 'username': username, 'password': password, 'blocking_timeout': 16 } #connexion à l'equipement net_connect = Netmiko(**equipment) with open('conf') as f: lines = f.read().splitlines() #envoi de la configuration output = net_connect.send_config_set(lines) net_connect.disconnect() print(output) print("Pensez à sauvegarder la configuration envoyée à l'équipement via la fonction 3" +"\n" ) duration(start)
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 cpy(): start = time.time() with open('router.list') as f: ip_r = f.read().splitlines() with open('switch.list') as f: ip_s = f.read().splitlines() ip_add = ip_r + ip_s #On parcourt la liste d'IP for ip in ip_add: print("Sauvegarde de la configuration de l'équipement ayant l'adresse : "+ ip) equipment = { 'device_type': 'cisco_ios', 'ip': ip, 'username': username, 'password': password, } #On initialise la connexion Netmiko sur l'équipement cible net_connect = Netmiko(**equipment) #Envoi d'un cpy run start sur l'équipement,utilisation de deux arguments permettant la confirmation de sauvegarde output = net_connect.send_command_timing("copy run start", strip_command=False, strip_prompt=False) output = net_connect.send_command_timing("startup-config", strip_command=False, strip_prompt=False) if "confirm" in output: output += net_connect.send_command_timing("y", strip_prompt=False, strip_command=False) net_connect.disconnect() print("Configuration sauvegardée avec succés") duration(start)
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 getHostInfo(host, user, passwd): net_connect = Netmiko( host, username=user, password=passwd, device_type="juniper_junos" ) commands = [ "show version | no-more", "show system alarms | no-more", "show chassis alarms | no-more", "show interfaces terse | match inet | match up", "show route 0.0.0.0", "request system storage cleanup dry-run | no-more", "show system storage detail | no-more", "show system config rescue | no-more", ] print("Logging in as " + user) print("*" * 30) print(net_connect.find_prompt()) print() for command in commands: print("*" * 30) print("Sending command: " + command) print(net_connect.send_command(command)) print("*" * 30) print("Logging out and closing session . . .") net_connect.disconnect()
def confgen(vars): # Generate configuration lines with Jinja2 with open(jinja_template) as f: tfile = f.read() template = jinja2.Template(tfile) cfg_list = template.render(vars) print('-' * 80) print(cfg_list) print('-' * 80) # Connect directly to host via telnet on the specified port conn = Netmiko(host=hostip, device_type='cisco_ios_telnet', port=vars['port']) # Check if host is in initial config state conn.write_channel("\n") time.sleep(1) output = conn.read_channel() if 'initial configuration dialog' in output: conn.write_channel('no\n') time.sleep(1) # Send generated commands to host output = conn.enable() output = conn.send_config_set(cfg_list) # Display results print('-' * 80) print('\nConfiguration applied on ' + vars['host'] + ': \n\n' + output) print('-' * 80) # Probably a good idea conn.disconnect()
def execute(device, commands, outputDirectory): executionStatus = False reasonForFailure = "NA" executionProtocol = "SSH" try: logging.info('verifying the existence of the output folder : %s', outputDirectory) if not os.path.exists(outputDirectory): logging.info( 'outputDirectory : %s not available, so creating one...') os.mkdir(outputDirectory) logging.info('started...') net_connect = Netmiko(**device) hostname = str(net_connect.find_prompt())[:-1] logging.info('prompt identified as : %s', net_connect.find_prompt()) output = 'Device IP : ' + device['host'] + '\n' logging.info( 'completed executing command, redirecting to output file %s', outFileName) outFile = open(outFileName, 'w') outFile.write(output) outFile.flush() outFile.close() logging.info('completed... disconnecting...') net_connect.disconnect() except: logging.error('exception in thread function for %s ip , stack : %s', threading.currentThread().getName(), traceback.extract_stack()) raise
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 configureHost(hosts, commands): # configures host with specific commands print("...\n...\n...") # connection handler to device user = input("Username: "******"%Y%m%d-%H%M%S") logName = timestr + ".log" logFile = open(logName, 'w') result = {"hosts": "Succes/Failed"} for host in hosts: print("configuring " + host) try: net_connect = Netmiko(host, username=user, password=pswd, device_type='cisco_ios') output = net_connect.send_config_set(commands) print(output) logFile.write(output) net_connect.disconnect() result[host] = "Success" except: result[host] = "Failed" continue for r in result: logFile.write(r + ": " + result[r] + "\n") logFile.close()
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 ap_migration(request): if os.path.exists('config_for_wlc.txt'): os.remove('config_for_wlc.txt') # provide list of selected AP: if request.method == "GET": return render(request, 'Migration_Website/ap_migration.html', {'context': ap_to_migration}) if request.method == "POST": wlc_name = request.POST.get['wlc_name'] wlc_ip = request.POST.get['wlc_ip'] config = open('config_for_wlc.txt', 'w+') for ap in ap_to_migration: config.write("config ap primary-base {} {} {} \n ".format(wlc_name, ap, wlc_ip)) config.close() ap_to_migration.clear() # Connect to controller and send commands: cisco1 = { "ip": ip_address "username": username1, "password": password1, "device_type": "cisco_wlc_ssh", 'global_delay_factor': 4, 'banner_timeout': 7 } net_connect = Netmiko(**cisco1) net_connect.send_config_from_file('config_for_wlc.txt') net_connect.disconnect() return HttpResponse("Udało się ?")
def main(): device_connection = Netmiko(**device) # Had to add the following to users ssh config file ~/.ssh/config: # # Host ios-xe-mgmt.cisco.com # KexAlgorithms=+diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1 # # otherwise the connection would fail due to no matching key exchanged method found. cli_output = device_connection.send_config_set(configuration) print(cli_output) # Transfer ZTP script file transfer_dict = file_transfer(device_connection, source_file=source, dest_file=destination, file_system='bootflash:', direction='put', overwrite_file=True) print(transfer_dict) device_connection.disconnect()
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 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)}")
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 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 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 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 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 config_change(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('config_change.txt') as commands: command = commands.read().splitlines() # g_output = net_connect.send_config_from_file(config_file="config_change.txt") g_output = net_connect.send_config_set(command) net_connect.disconnect() return "-----------Working on host " + ips + " -----------\n" + g_output + "\n" # except ValueError: except NetMikoTimeoutException: w = open('status_output.txt', 'a') w.write("ERROR: connection to " + ips + " timed-out.") w.close() except NetMikoAuthenticationException: k = open('status_output.txt', 'a') k.write("ERROR: Authentication failed for " + ips) k.close()
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 function_capture(data_dir, command_dir, capture_path): book = xlrd.open_workbook(data_dir) first_sheet = book.sheet_by_index(0) cell = first_sheet.cell(0, 0) book_command = xlrd.open_workbook(command_dir) first_sheet_command = book_command.sheet_by_index(0) cell_command = first_sheet_command.cell(0, 0) for i in range(first_sheet.nrows): my_device = { "host": first_sheet.row_values(i)[1], "username": first_sheet.row_values(i)[2], "password": first_sheet.row_values(i)[3], "secret": first_sheet.row_values(i)[4], "device_type": first_sheet.row_values(i)[5], } print('Device Executed :') print(first_sheet.row_values(i)[0] + ' ' + my_device["host"]) write = open( capture_path + '/' + first_sheet.row_values(i)[0] + '-' + first_sheet.row_values(i)[1] + '.txt', 'w') try: net_connect = Netmiko(**my_device) #key information about device write.write(first_sheet.row_values(i)[5] + '\n') #show command for command in range(first_sheet_command.nrows): if my_device["device_type"] in first_sheet_command.row_values( command)[0]: count_column = 1 #while count_column < 8: for cmd in (first_sheet_command.row_values(command, start_colx=0, end_colx=None)): try: output = net_connect.send_command( first_sheet_command.row_values(command) [count_column]) print( first_sheet_command.row_values(command) [count_column]) print(output) write.write( first_sheet_command.row_values(command) [count_column] + '\n') write.write(output + '\n') count_column += 1 except: pass #disconnect netmiko net_connect.disconnect() except: write.write('Cannot Remote Device')
#!/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) # Ensure in enable mode net_connect.enable() print(net_connect.find_prompt()) net_connect.disconnect()