def deviceconnector(i, q): # This while loop runs indefinitely and grabs IP addresses from the queue and processes them # Loop will be blocked and wait if "ip = q.get()" is empty while True: ip = q.get() with print_lock: print('Th{}/{}: Acquired IP: {}'.format(i+1, threads, ip)) #Create an error log file errorfile = open('valkyrie output/valkyrie errors ' + str(date.today()) + '.txt', 'a') # device_dict is copied over to net_connect device_dict = { 'host': ip, 'username': username, 'password': password, 'secret': secret, 'device_type': 'autodetect', 'banner_timeout': 60, 'conn_timeout': 60 # Gather session output logs - TESTING ONLY # , # 'session_log': 'session_output.txt' } # device type autodetect based on netmiko try: auto_device_dict = SSHDetect(**device_dict) device_os = auto_device_dict.autodetect() # Validate device type returned (Testing only) # print('===== {} =====\n===== {} ====='.format(device_os, auto_device_dict.potential_matches)) # Update device_dict device_type from 'autodetect' to the detected OS if device_os is None: print('Th{}/{}: {} returned unsupported device_type of {}\n'.format(i + 1, threads, device_dict['host'], device_os)) device_dict['device_type'] = 'autodetect' else: device_dict['device_type'] = device_os # Connect to the device, and print out auth or timeout errors net_connect = Netmiko(**device_dict) print('Th{}/{}: Connecting to: {} ({})'.format(i+1, threads, net_connect.host, net_connect.device_type)) except NetMikoTimeoutException: with print_lock: print('Th{}/{}: ERROR: Connection to {} timed-out. \n'.format(i+1, threads, ip)) errorfile.write('[{}] {} ERROR: Connection timed-out. \n'.format(datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() except (NetMikoAuthenticationException, AuthenticationException): with print_lock: print('Th{}/{}: ERROR: Authentication failed for {}. Stopping thread. \n'.format(i+1, threads, ip)) errorfile.write('[{}] {} ERROR: Authentication failed. \n'.format(datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() except NoValidConnectionsError: with print_lock: print('Th{}/{}: ERROR: No Connections available for device {}. \n'.format(i+1, threads, ip)) errorfile.write('[{}] {} ERROR: No Connections available. \n'.format(datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() # Capture the output # TODO TextFSM to parse data # create two variables - one of hostname and the prompt level and another with just the hostname prompt = net_connect.find_prompt() hostname = prompt.rstrip('#>') print('Th{}/{}: Associated IP: {} with hostname: {}'.format(i+1, threads, ip, hostname)) # TODO Write file to a optional, specified folder timenow = '{:%Y-%m-%d %H_%M_%S}'.format(datetime.now()) start = datetime.now() filename = (hostname + ' ' + ip + ' - valkyrie output {0}.txt') outputfile = open('valkyrie output/' + filename.format(timenow), 'w') print('Th{}/{}: Writing file name "{} {} - valkyrie output {}.txt"'.format( i+1, threads, hostname, ip, format(timenow))) if device_os == 'cisco_ios': for cmd in commands: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_nxos': for cmd in commands_nexus: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_wlc': for cmd in commands_wlc: try: if re.match(r'\w', cmd): if cmd == 'show run-config': output = net_connect.send_command_timing(cmd.strip(), delay_factor=1, max_loops=1000) if 'Press Enter to continue' in output: output += net_connect.send_command_timing('\n') write_file(outputfile, prompt, cmd, output) else: output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_asa': for cmd in commands_asa: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) else: for cmd in commands_showtech: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) # Disconnect from device net_connect.disconnect() # Close the file outputfile.close() # errorfile.write('Closing file...') errorfile.close() # verify elapsed time per device end = datetime.now() print('Th{}/{}: Completed. Time elapsed: {}'.format(i+1, threads, (end-start))) # Set the queue task as complete, thereby removing it from the queue indefinitely q.task_done()
from netmiko import Netmiko from getpass import getpass import datetime device = { 'host': 'nxos1.lasthop.io', 'username': '******', 'password': getpass(), 'device_type': 'cisco_nxos', 'session_log': 'global_factor.txt', 'global_delay_factor': 2 } net_connection = Netmiko(**device) print(net_connection.find_prompt()) begin_time = datetime.datetime.now() output = net_connection.send_command("show lldp neighbors") print(output) print(datetime.datetime.now()) print(datetime.datetime.now() - begin_time) begin_time = datetime.datetime.now() output1 = net_connection.send_command("show lldp neighbors", delay_factor=8) print(output1) print(datetime.datetime.now()) print(datetime.datetime.now() - begin_time) print(net_connection.find_prompt())
#!/usr/bin/env python from netmiko import Netmiko # SSH Connection Details ios1 = { 'device_type': 'cisco_ios', 'ip': '198.18.1.55', 'username': '******', 'password': '******', } # Establish SSH to device and run config command net_connect = Netmiko(**ios1) output = net_connect.send_config_set('logging host 10.1.1.1') print(output)
from netmiko import Netmiko from getpass import getpass ip_addr = sys.argv[1] username = sys.argv[2] my_device = { 'host': ip_addr, 'username': username, 'password': getpass(), 'device_type': 'cisco_ios' } cfg_commands = ['logging buffered 10000', 'no logging console'] net_conn = Netmiko(**my_device) cfg_cmds_output = net_conn.send_config_set(cfg_commands) cfg_file_output = net_conn.send_config_from_file('config.txt') print(cfg_file_output) sh_run_output = net_conn.send_command('show running-config all | i logging') if cfg_commands[0] in sh_run_output and cfg_commands[1] in sh_run_output: print("Commands committed successfully!") else: print("Commands not committed.") net_conn.disconnect()
def show_ip_int_brief(device): net_conn = Netmiko(**device) print("This is for the device", device['ip']) output = net_conn.send_command("show ip int brief") print(output)
print("vlan " + str(i)) print("name wireless_user-v"+ str(i)) print("tagged 3") for i in range(150,200): print("vlan " + str(i)) print("name server-v"+ str(i)) print("tagged 3") for i in range(200,250): print("vlan " + str(i)) print("name wired_user-v"+ str(i)) print("tagged 3") # close the file, stop redirecting stdout sys.stdout.close() sys.stdout = orig_stdout # setup Netmiko switch = { 'host': '10.139.146.3', 'username': '******', 'password': '******', 'device_type': 'hp_procurve', } switchconnect = Netmiko(**switch) switchconnect.enable() # run Netmiko, print what happens on switch, disconnect output = switchconnect.send_config_from_file("switchfile") print(output) switchconnect.disconnect()
#!/usr/bin/env python3 from netmiko import Netmiko from getpass import getpass import logging import time logging.basicConfig(filename='test.log', level=logging.DEBUG) logger = logging.getLogger("netmiko") # Credential in GNS3 : admin, admin123 password = getpass(prompt="Password : "******"show ip arp") print(output) print(type(output)) net_conn.write_channel("show ip arp\n") time.sleep(15) outout = net_conn.read_channel("show ip arp\n") print(output) print(type(output))
import re from netmiko import Netmiko src_ip = '10.1.7.1' src = Netmiko( ip=src_ip, username="******", password="******", device_type="cisco_ios", ) print("Connected") time = src.send_command("show clock").split(" ")[3:5] time = time[0] + " " + time[1] print(time) #ret = src.send_command("show log | i down|Down|up|Up|err|fail|Fail|drop|crash|MALLOCFAIL|duplex",time[0]+" "+str((int(time[1])-1))) ret = src.send_command("show log | i " + time) arr = ret.split('\n') count = 0 syslog = dict() for line in arr: if line.find('%') != -1 and (line.find("NBRCHANGE") != -1 or line.find("ADJCHANGE") != -1 or line.find("UPDOWN") != -1 or line.find("duplex") != -1): syslog.update({count: line}) count += 1 print(syslog)
#! /usr/bin/env python3 """Connects to a device using Netmiko and prints the prompt Usage: python ex-1.py Output: Password: cisco1# Author: Bradley Fernando """ from netmiko import Netmiko from getpass import getpass cisco1 = { "device_type": "cisco_ios", "host": "cisco1.lasthop.io", "username": "******", "password": getpass() } net_conn = Netmiko(**cisco1) print(net_conn.find_prompt())
def main(): timestamp = datetime.now().strftime('%Y%m%d%H%M%S') # get list of IPs to generate port report from while True: try: input_ips = input("Enter a space delimited list of device IPs: ").split() for i in range(0, len(input_ips)): input_ips[i] = ipaddress.ip_address(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: '******'/port_report_'+timestamp+'.csv', 'w') as csv_file, open(os.getcwd()+'/port_report_'+timestamp+'.html', 'w') as html_file: report_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) report_writer.writerow(['Hostname', 'Interface', 'Status', 'Description']) html_file.write("<html>\n<head>\n<title>Cisco Switchport Report</title>\n") html_file.write("<style>\n* { padding: 8px; margin: 0; border: 0px; border-spacing: 0px; }\ntr { border-bottom: 1px solid #ccc; }\ntr:first-child { font-weight: bold; }\ntr:nth-child(odd) { background-color: #f2f2f2; }\n</style>\n") html_file.write("</head>\n<body>\n<table>\n<tr>\n<td>Hostname</td>\n<td>Interface</td>\n<td>Status</td>\n<td>Description</td>\n</tr>\n") for ip in input_ips: conn = { "host": str(ip), "username": cisco_user, "password": cisco_pass, "device_type": "cisco_ios", } 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] if "Nexus" in vers: int_list = net_connect.send_command('show interface brief') else: int_list = net_connect.send_command('show ip interface brief') for j in int_list.splitlines(): if "down" not in j and "up" in j: status = "up" else: status = "down" desc = " " int_conf = net_connect.send_command("show run int "+j.split()[0]) for k in int_conf.splitlines(): if "description" in k: desc = k[13:] report_writer.writerow([hostname, j.split()[0], status, desc]) html_file.write("<tr>\n<td>"+hostname+"</td>\n<td>"+j.split()[0]+"</td>\n<td>"+status+"</td>\n<td>"+desc+"</td>\n</tr>\n") print(f"Process completed on {str(ip)}") net_connect.disconnect() html_file.write("</table>\n</body>\n</html>")
from netmiko import Netmiko username = '******' password = '******' hostname = 'cisco4.lasthop.io' device = { 'host': hostname, 'username': username, 'password': password, 'device_type': 'cisco_ios', } conn = Netmiko(**device) print(conn.find_prompt()) command = 'ping' output = conn.send_command(command, expect_string='Protocol', strip_prompt=False, strip_command=False) output += conn.send_command('\n', expect_string='Target IP address', strip_prompt=False, strip_command=False) output += conn.send_command('8.8.8.8', expect_string='Repeat count', strip_prompt=False, strip_command=False) output += conn.send_command('\n', expect_string='Datagram size',
from netmiko import Netmiko print('Before Connection') host = input("Enter Firewall IP/Hostname:") connection = Netmiko(host=(host), port ='22', username='******', password='******', device_type='fortinet') enter_vdom_config_mode = connection.send_config_set('config global') edit_vdom = connection.send_config_set('get system vdom-property | grep name:') print(edit_vdom)
from __future__ import unicode_literals from netmiko import Netmiko from getpass import getpass csr1000v = { 'device_type':'cisco_ios', 'username':'******', 'password': getpass(), 'ip':'192.168.8.128' } connection = Netmiko(**csr1000v) print connection.find_prompt()
border: 1px solid black; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style>''') now = str(datetime.datetime.now()) try: mlselr01ebr01 = util.CiscoDeviceRO(host="mlselr01ebr01") mlsctc01ebr01 = util.CiscoDeviceRO(host="mlsctc01ebr01") ping1 = () while len(ping1) <= 50: net_connect1 = Netmiko(**mlselr01ebr01.__dict__) net_connect2 = Netmiko(**mlsctc01ebr01.__dict__) ping1 = net_connect1.send_command("ping " + hostname + " count 100") ping2 = net_connect2.send_command("ping " + hostname + " count 100") if len(ping1) <= 50: print("Could not resolve servername. Please try again.") else: print('<br />') server_ip1 = ping1.splitlines()[2].split()[3][:-1] server_ip2 = ping2.splitlines()[2].split()[3][:-1] trace1 = net_connect1.send_command("traceroute " + server_ip1) access1 = util.acc_sw(trace1) access2 = util.acc_pair(access1) except: print( "An exception occurred in ping testing from Core network, program exiting"
### Configuring a Networking Device from a File from netmiko import Netmiko connection_object = Netmiko(device_type='cisco_ios', host='192.168.128.129', port=22, username='******', password='******', secret='automation') print(' \n *** Entering Enable Mode *** \n') connection_object.enable() ## Netmiko offers us a method called SEND_CONFIG_FROM_FILE and it send all from that file into SSH connection print(' ... Sending commands from file ospf.txt ...\n') output_var = connection_object.send_config_from_file( 'ospf.txt ') ## the ARGUMENT will be file ospf.txt print(output_var) print(' \n *** Closing the connection *** ') connection_object.disconnect()
sys.exit(1) USER = input("Enter username: "******"Enter password: "******"Connecting... " + HOST + "\n") try: net_connect.enable() output = net_connect.send_config_from_file("config_file.txt") print(output) except: print("Failed configuring!") except: print("Failed connecting!") sys.exit(1) print("Closing connections...") net_connect.disconnect() print("Done!")
#Creates a border for better separation. def boarder(): print('+' * 60) print('\n') username = '******' password = '******' os = 'juniper_junos' boarder() for host in hosts_list: print(host) device = Netmiko(device_type=os, ip=host, username=username, password=password) output = device.send_command( 'show ethernet-switching table | match xx:xx:xx:xx', delay_factor=5) #output = device.send_command_expect("show ethernet-switching table | match 24:db:ad") print(output) print(host, output, file=open("output.txt", "a")) device.disconnect() boarder() exit() #Code to just do one device. # core = { # 'host': '0.0.0.0', # 'username': '******',
inventory['g20_netmask'] = vals['G2/0 Netmask'] inventory['device_type'] = vals['Device type'] inv_list.append(inventory.copy()) for items in inv_list: print('\nCurrent device: ' + items['device']) with open(jinja_template) as f: tfile = f.read() template = jinja2.Template(tfile) cfg_list = template.render(items).split('\n') conn = Netmiko(host=items['ip'], device_type=items['device_type'], username=items['username'], password=items['password'], port=items['port']) 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) output = conn.enable() output = conn.send_config_set(cfg_list) print(output)
from netmiko import Netmiko username = '' password = '' nxos1 = { 'host': 'nxos1.lasthop.io', 'username': username, 'password': password, 'device_type': 'cisco_nxos', } nxos2 = { 'host': 'nxos2.lasthop.io', 'username': username, 'password': password, 'device_type': 'cisco_nxos', } devices = [nxos1, nxos2] for dev in devices: conn = Netmiko(**dev) output = conn.send_config_from_file('config.txt') conn.save_config() print(output) conn.disconnect()
def main(): #timestamp = datetime.now().strftime('%Y%m%d%H%M%S') # gather list of device IPs used to generate VLAN list while True: try: dev_ips = input( "Enter a space delimited list of device IPs: ").split() for i in range(0, len(dev_ips)): dev_ips[i] = ipaddress.IPv4Address(dev_ips[i]) except: if input( "Invalid data entered. Press any key to continue or 'q' to quit. " ) == 'q': exit() else: break if len(dev_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 dev_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: sys.stdout.write("!") sys.stdout.flush() else: hostname = net_connect.find_prompt().split('#')[0] with open(f'{os.getcwd()}/{hostname}_vlans.csv', 'w') as csv_file: report_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) report_writer.writerow( ['VLAN ID', 'VLAN Description', 'Subnet']) vlans = net_connect.send_command("show vlan brief") for vlan in vlans.splitlines(): if len(vlan) > 0 and vlan.split()[0].isdigit(): vlan_id = vlan.split()[0] vlan_desc = vlan.split()[1] subnet = "NA" svi = net_connect.send_command( f"show run interface Vlan{vlan_id}") for line in svi.splitlines(): if line.lstrip().startswith("ip address "): if len( line.lstrip("ip address").strip(). split()) > 1: subnet = ipaddress.ip_network( f"{line.lstrip('ip address').strip().split()[0]}/{line.lstrip('ip address').strip().split()[1]}", strict=False) else: subnet = ipaddress.ip_network( line.lstrip("ip address").strip(), strict=False) report_writer.writerow( [vlan_id, vlan_desc, str(subnet)]) net_connect.disconnect() sys.stdout.write(".") sys.stdout.flush()
#!/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 = "del flash:/test1.txt" print() print(net_connect.find_prompt()) output = net_connect.send_command_timing(command) if "confirm" in output: output += net_connect.send_command_timing("y", strip_prompt=False, strip_command=False) net_connect.disconnect() print(output) print()
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass pub_key = "/home/tarmstrong/.ssh/test_sshkey.pub" # pub_key = "/home/melshman/.ssh/id_rsa.pub" # password = getpass() VTswitch = { 'device_type': 'cisco_ios', 'host': '192.168.2.101', 'username': '******', 'use_keys': True, 'key_file': pub_key, } pynet_rtr1 = { 'device_type': 'cisco_ios', 'host': '184.105.247.70', 'username': '******', 'use_keys': True, 'key_file': pub_key, # 'password' = password } # net_connect = Netmiko(**VTswitch) net_connect = Netmiko(**pynet_rtr1) print(net_connect.find_prompt()) output = net_connect.send_command("show version") print(output)
def show_arp(device): net_conn = Netmiko(**device) print("This is for the device", device['ip']) output = net_conn.send_command("show arp") print(output)
userMAC = input("\nPlease enter the MAC address you would like to search. Must be HHHH.HHHH.HHHH format: ") deviceName = input("Please enter the IP of the switch you would like to search: ") # connect to user's choice while True: try: username = input("Username: "******"Logging in now...") net_connect = Netmiko(**myDevice) net_connect.enable() break except: print("Login failed. Please try again.\n") continue print ('Searching MAC address...') # check to see if the MAC is on the distro and grab some variables while True: # issue show mac add add userMAC showMAC = net_connect.send_command('show mac add add ' +userMAC) # checks to see if we get correct output if 'Unicast Entries' in showMAC: # splits output into strings
from netmiko import Netmiko username = "******" password = "******" individual_host = "10.128.0.26" # Here we create a Netmiko object. The Netmiko library is expecting a # list of keyword arguments, like this: net_connect = Netmiko(host=individual_host, username=username, password=password, device_type='cisco_ios') # Use Netmiko to send the command to the device. Capture the output of # the command in the variable "output". netmiko_command = "show ip int brief" netmiko_output = net_connect.send_command(netmiko_command) # Close the connection. net_connect.disconnect() # Display the response send back from the device in the Python console. print("--- Begin Netmiko output for " + individual_host + " ---") print(netmiko_output) print("--- End Netmiko output for " + individual_host + " ---")
Output: configure terminal Enter configuration commands, one per line. End with CNTL/Z. cisco1(config)#logging buffered 100000 cisco1(config)#end cisco1#write mem Building configuration... [OK] cisco1# Author: Bradley Fernando """ from netmiko import Netmiko from getpass import getpass password = getpass() cisco1 = { "device_type": "cisco_ios", "host": "cisco1.lasthop.io", "username": "******", "password": password } commands = ["logging buffered 100000"] with Netmiko(**cisco1) as net_connect: output = net_connect.send_config_set(commands) output += net_connect.save_config() print(f"\n{output}\n")
for host in device["lista_host"]: plataform = maps_so[host["plataforma"]] # Abrimos nuestro archivo con las variables para cargar la configuracion with open(f"hosts_vars/{plataform}_conf.yml", "r") as handle: ntps = safe_load(handle) # Creamos el entorno para jinja2 jinja_env = Environment(loader=FileSystemLoader("."), trim_blocks=True, autoescape=True) template = jinja_env.get_template(f"templates/{plataform}_ntp.j2") nueva_config = template.render(data=ntps) pdb.set_trace() # realizamos la conexión con Netmiko conexion = Netmiko( host=host["name"], username="******", password="******", device_type=plataform, ) print(f"Ingresando en el equipo {conexion.find_prompt()}, corectamente") resultado = conexion.send_config_set(nueva_config.split("\n")) print(resultado) conexion.close()
} td, th { border: 1px solid black; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style>''') now = str(datetime.datetime.now()) switch = util.CiscoDeviceRO(host=hostname) net_connect = Netmiko(**switch.__dict__) nxos_check = net_connect.send_command("show version") if "NX-OS" in nxos_check: sw_ver = "nxos" else: sw_ver = "ios" name_port = {} ports_input = net_connect.send_command("show interface status | i connected") ports_connected = ports_input.splitlines() portcount = str(len(ports_connected)) print("<table><caption>" + hostname + "</caption>") for line in ports_connected: if "mls" not in line and "Vlan" not in line and "SPAN" not in line and "Lo0" not in line: port = line.split(' ')[0] print("<tr><td>" + port + "</td>") desc = net_connect.send_command("show interface " + port +
from netmiko import Netmiko from getpass import getpass from pprint import pprint def output_printer(output): print() print('-' * 80) print(output) print('-' * 80) print() try: host = raw_input("Enter host to connect to: ") except NameError: host = input("Enter host to connect to: ") password = getpass() device = { 'host': host, 'username': '******', 'password': password, 'device_type': 'cisco_ios', } command = 'show ip int brief' net_connect = Netmiko(**device) output = net_connect.send_command(command, use_textfsm=True) output_printer(output)
print("This is the IP/hostname you have entered - ", user_input) input_db = read_db.parse(0) search_ip = input_db.loc[(input_db["Host_Name"] == user_input) | (input_db["Mgt_IP_Address"] == user_input), "Mgt_IP_Address"] out_ip = search_ip.to_string(index=False) ip = out_ip Devices = { 'device_type': 'cisco_ios', 'host': ip, 'username': '******', 'password': '******', 'port': 22, 'secret': '', 'auth_timeout': 20 } net_connect = Netmiko(**Devices) time.sleep(20) cfg_file = "configfile.txt" print() print(net_connect.find_prompt()) output = net_connect.enable() output = net_connect.send_config_from_file(cfg_file) print(output) print() net_connect.save_config() net_connect.disconnect()