from netmiko import ConnectHandler # Create device dictionaries wlc01 = { 'device_type': 'aruba_os', 'ip': '192.168.1.10', 'username': '******', 'password': '******', } # Establish secure session to device net_connect = ConnectHandler(**wlc01) # Send command to create backup file and wait 2 seconds for backup to complete net_connect.send_command('backup flash', delay_factor=2) # Send command to copy backup file to backup server via ftp cmd1 = 'copy flash: flashbackup.tar.gz ftp: 172.16.1.100 ftpusername /backups flashbackup.tar.gz' output = net_connect.send_command_timing(cmd1) if 'Password:'******'ftpuserpassword') # Disconnect secure session from device net_connect.disconnect()
#!/usr/bin/env python from netmiko import ConnectHandler from getpass import getpass ios_xe = { 'host': 'cisco3.lasthop.io', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', 'session_log': 'ios_xe.txt', } nx_os = { 'host': 'nxos1.lasthop.io', 'username': '******', 'password': getpass(), 'device_type':'cisco_ios', 'session_log': 'nx_os.txt', } devices = [ios_xe, nx_os] for device in devices: net_connect = ConnectHandler(**device) print(net_connect.find_prompt()) print(net_connect.send_command('show version'))
from netmiko import ConnectHandler # Borra interface sshCli = ConnectHandler ( device_type = 'cisco_ios', host = '192.168.56.101', port = 22, username = '******', password = '******' ) Int_name = input("Nombre de la interface a borrar: ") config_commands = [ 'no int ' + Int_name, ] output = sshCli.send_config_set(config_commands) ## ##from ncclient import manager ##import xml.dom.minidom ## ##m = manager.connect ( ## host="192.168.56.101", ## port=830, ## username="******", ## password="******", ## hostkey_verify=False ## ) ##
TIMEOUT = int(input("How long shoud the Capture run [sec]: ")) SCP_IP = input("IP-SCP-Server: ") SCP_USERNAME = input("Enter your SCP-Username: "******"Enter your SCP-Password: "******"device_type": "cisco_ios", "ip": IP_ADDRESS_OF_DEVICE, "username": USERNAME, "password": PASSWORD, } for i in range(1, 2): try: net_connect = ConnectHandler(**IOS) except (AuthenticationException): print("Authentication failure: " + IP_ADDRESS_OF_DEVICE) continue except (NetMikoTimeoutException): print("Timeout to device: " + IP_ADDRESS_OF_DEVICE) continue except (EOFError): print("End of file while attempting device: " + IP_ADDRESS_OF_DEVICE) continue except (SSHException): print("SSH Issue. Are you sure SSH is enabled?: " + IP_ADDRESS_OF_DEVICE) continue except Exception as unknown_error: print("Some other error " + IP_ADDRESS_OF_DEVICE)
f"ip route {self.route} {self.subnet_mask} {self.interface} {self.gateway}" ] ios_connection.send_config_set(config_commands) #Get user to fill in there details ios_connection_details = {"device_type": "cisco_ios"} input_ip_addr = input("Input the IP/DNS of the CUBE: ") input_username = input("Input username: "******"input password: "******"ip"] = input_ip_addr ios_connection_details["username"] = input_username ios_connection_details["password"] = input_password ios_connection = ConnectHandler(**ios_connection_details) #Build SSH for NAPALM driver = get_network_driver("ios") iosvl2 = driver(f"{input_ip_addr}", f"{input_username}", f"{input_password}") iosvl2.open() #Verify interfaces for users output = ios_connection.send_command("show ip int brief") print(output) #Verify the internal/external interfaces for CUBE internal_cube_interface = input( "Specify the internal interface as listed above: ") external_cube_interface = input( "Specify the external interface as listed above: ")
equipo = { 'device_type': 'cisco_ios', #Tipo de equipo 'host': ipadd, # IP MGT 'username': username, 'password': password, 'port': port, # optional, defaults to 22 'global_delay_factor': 3, } ############################################################################## # Connect using SSH print("Connecting : (" + ipadd + ")\n") net_connect = ConnectHandler( **equipo ) # envio a la funcion ConnectHandler el argumento **Equipo guardo la conexion en la variable net_connect # Get Hostname from Session hostname = net_connect.find_prompt() print("Hostname", hostname) cmd = net_connect.send_command('show version') print(cmd) file = open("Show_Version", "w") # AQUI Estoy abriendo el archivo file.write(cmd) file.close() comandos = ['show version', 'show inventory', 'show run', 'show hola']
'password': '******', } routerDown = { 'device_type': 'cisco_ios', 'host': '40.40.40.10', 'username': '******', 'password': '******', } #putting targted routers in list for looping allDevices = [routerRight, routerLeft, routerDown] start_time = datetime.now() for device in allDevices: connection = ConnectHandler(**device) connection.enable() #targeted output rmodel = connection.send_command("show version | in revision") hostname = connection.send_command("show run | in hostname") uptime = connection.send_command("show version | in uptime") sversion = connection.send_command("show version | in Version") hwSerial = connection.send_command("show Inventory | in Hw") # mac = connection.send_command("show interfaces | in Gi.*up|bia") mac = connection.send_command("show ip arp | in -", use_textfsm=True) #putting output in Dic for parsing device = { 'HOSTNAME ': hostname, 'MODEL ': rmodel,
from netmiko import ConnectHandler #R1 eh cisco IOS e R2 e JunOS, em R2 definimos uma senha de secret de nula #O ideal eh que exista um usuario com privilege 15 em R1 R1={'so':'cisco_ios','hostname':'R1','ip':'1.1.1.1','user':'******','pass':'******','secret':'cisco','command':'show run'} R2={'so':'juniper','hostname':'R2','ip':'2.2.2.2','user':'******','pass':'******','secret':'','command':'show configuration'} #Lista Vazia onde seram armazenados os comandos de configuracao dos arquivos comandosdeconf=[] #Lista de diccionarios MyRouters=[R1,R2] for router in MyRouters: #Definindo Connect Handler router_connect=ConnectHandler(device_type=router['so'],ip=router['ip'],username=router['user'],password=router['pass'],secret=router['secret'],timeout=10) #Se o roteador eh ios, mudo para enable if router['so'] == 'cisco_ios' : router_connect.enable() #Envio o comando output=router_connect.send_command(router['command']) #Crio o arquivo e armazeno o resultado arquivosaida=router['ip'] + '.txt' with open(arquivosaida,'w') as fh: fh.write(output) #Saio do enable se eh Cisco IOS if router['so'] == 'cisco_ios' :
from netmiko import ConnectHandler cisco_gns3 = { 'device_type': 'cisco_ios', 'ip': '10.10.10.30', 'username': '******', 'password': '******' } connection = ConnectHandler(**cisco_gns3) hostname = connection.find_prompt() print(hostname[:-1]) interface_name = connection.send_command('show run int eth0/0 | i ^ interface') print(interface_name) interface_description = connection.send_command( 'show run int eth0/0 | i ^ des') if not interface_description: interface_description = 'N/A' print(interface_description) Config1 = ['interface loopback0', 'ip address 100.100.100.100 255.255.255.255'] connection.config_mode() create_loopback = connection.send_config_set(Config1) print(create_loopback) verification = connection.send_command( 'show ip interface brief | include Loopback')
"password": getpass(), "device_type": 'cisco_ios', #"fast_cli": True, "session_log": './session_logs/session_log_nxos1.txt', } host_nxos2 = { "host": 'nxos2.lasthop.io', "username": '******', "password": getpass(), "device_type": 'cisco_ios', #"fast_cli": True, "session_log": './session_logs/session_log_nxos2.txt', } host_connect = ConnectHandler(**host_nxos1) configure_vlans = [ 'vlan 100', 'vlan 101', 'vlan 102', ] #datetime_now = datetime.now() #print('Current DATE and TIME ---------------->: ' + str(datetime_now) + '\n') #output = host_connect.send_config_set(configure_name_server) output = host_connect.send_config_from_file( config_file='pyscripts/week_02/vlans.txt') print(output) print('\n')
def connect(self): return ConnectHandler(**self.netmiko_device_details)
def ssh_conn(device, show_command): net_connect = ConnectHandler(**device) return net_connect.send_command(show_command) net_connect.disconnect()
#!/usr/bin/env python #Get running-config from nxos in lab from __future__ import print_function, unicode_literals from netmiko import ConnectHandler from datetime import datetime from getpass import getpass cisco_nxos1 = { 'device_type': 'cisco_nxos', 'ip': 'nxos1.lasthop.io', 'username': '******', 'password': getpass(), 'port': 22, #'session_log': 'my_session.txt' } net_connect = ConnectHandler(**cisco_nxos1) #Ensure enable mode net_connect.enable() print(net_connect.find_prompt()) #output = net_connect.send_command('show version') #print (output) #net_connect.disconnect()
# import netmiko from netmiko import ConnectHandler # from getpass import getpass from time import ctime password = input("Digite password") centos_vm = { 'device_type': 'linux', 'host': '192.168.77.66', 'username': '******', 'password': password } net_connect = ConnectHandler(**centos_vm) # net_connect = ConnectHandler(device_type='linux', host='192.168.77.66', username='******', password=password) net_connect.find_prompt() net_connect.send_command("mkdir hola" + str(ctime()).replace(" ", "_s")) output = net_connect.send_command("ip addr") print(output)
def show_hsrp(SWITCHES): print("Fetching HSRP statuts from SWITCHES") for SWITCH in SWITCHES: net_connect = ConnectHandler(**SWITCH) output = net_connect.send_command_expect('show standby') print(output)
"fast_cli": True } nxos2 = { "host": "nxos2", 'username': '******', 'password': getpass(), 'device_type': 'cisco_nxos', 'session_log': 'nxos2_5.txt', 'fast_cli': True } device = [nxos1, nxos2] t0 = datetime.now() for d in device: t1 = datetime.now() ssh_con = ConnectHandler(**d) ssh_con.send_config_from_file('ex5_commands.txt') ssh_con.save_config() ssh_con.disconnect() t2 = datetime.now() t3 = t2 - t1 print("\nINICIO: ", t1) print('\nFIN: ', t2) print('\nDuracion ejecucion comando: ', t3) tf = datetime.now() print('\nDuracion configuracion equipos: ', tf - t0)
#Defining the device type for running netmiko (SSH management to Network Devices) device_type = 'arista_eos' #Defining the username and password for running netmiko username = '******' password = '******' #Defining the command to send to each device command = 'show running' command1 = 'show ip int brief' #Connecting to the device via SSH session = ConnectHandler(device_type=device_type, ip=ip, username=username, password=password, global_delay_factor=3) #Entering enable mode enable = session.enable() #Sending the commands and storing the output (running configuration) output = session.send_command(command) output += session.send_command(command1) #Defining the file from yesterday, for comparison. device_cfg_old = 'cfgfiles/' + ip + '_' + ( datetime.date.today() - datetime.timedelta(days=1)).isoformat() #Writing the command output to a file for today.
# Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode). from netmiko import ConnectHandler from getpass import getpass rtr2 = { 'device_type':'cisco_ios','ip':'184.105.247.71','username':'******', 'password':'******'} pynet_rtr2 = ConnectHandler(**rtr2) pynet_rtr2.config_mode() print ('Are we in config mode for pynet_rtr2?') print (pynet_rtr2.check_config_mode())
ROUTERS_FILE = "routers.json" PATH = "/home/bucko" #Import modules import json from netmiko import ConnectHandler if __name__ == "__main__": with open(PATH + "/" + ROUTERS_FILE) as json_f: device_list = json.load(json_f) # Find device's index for device_index, routers_dict in enumerate(device_list["routers"]): if router in routers_dict["host"]: routers_index = device_index break # print("cisco4 router is {}. item in list and iths FQDN is: {}".format(routers_index,device_list["routers"][routers_index]["host"])) with ConnectHandler( **device_list["routers"][routers_index]) as router_session: output = router_session.send_command_timing("ping") if "Protocol" in output: output += "\n" + router_session.send_command_timing("\n") if "Target" in output: output += DESTINATION + "\n" + router_session.send_command_timing( DESTINATION) if "Repeat count" in output: for i in range(5): output += "\n" + router_session.send_command_timing( "\n") print(output)
from netmiko import ConnectHandler import time # Python code to illustrate Sending mail from # you import smtplib from prettytable import PrettyTable F5_LTM = { 'device_type': 'f5_ltm', 'ip': '10.1.0.2', 'username': '******', 'password': '******', 'port': '22' # optional, defaults to 22 } net_connect = ConnectHandler(**F5_LTM) #output = net_connect.find_prompt() #o1=net_connect.config_mode() #output2 = net_connect.send_command("tmsh \n") #print (" Collecting F5 Version ") o12 = str( "=============================F5 LTM Version=============================") output12 = net_connect.send_command(' show sys version') int0 = output12.index('12.') Vr = (output12[int0:int0 + 8]) str1 = str("F5 LTM Version") #print str1+Vr
'''In the lab environment use Netmiko to connect to one of the Cisco NX-OS devices. You can find the IP addresses and username/passwords of the Cisco devices in the 'Lab Environment' email or alternatively in the ~/.netmiko.yml file. Simply print the router prompt back from this device to verify you are connecting to the device properly.''' from netmiko import ConnectHandler nxos1_dict = { "host": "nxos1.lasthop.io", "username": "******", "password": "******", "device_type": "cisco_nxos" } nxos1_connect = ConnectHandler(**nxos1_dict) print(nxos1_connect.find_prompt()) nxos1_connect.disconnect()
'device_type': 'cisco_ios', 'ip': ip_info, 'username': '******', 'password': '******', 'secret': 'enable', 'verbose': False, } if gateway_info[gt_counter][1] == 'CALL': logfile = open( "/home/GTSesMon/PycharmProjects/SIPGatewayLog/siplog_1001302", "w") elif gateway_info[gt_counter][1] == 'VIDEO': logfile = open( "/home/GTSesMon/PycharmProjects/SIPGatewayLog/siplog_14412", "w") net_connect = ConnectHandler(**cisco_router) prompt_text = net_connect.find_prompt() print(prompt_text) if prompt_text != '': net_connect.enable() if gateway_info[gt_counter][1] == 'CALL': output = net_connect.send_command( 'sh call history voice brief | i :') elif gateway_info[gt_counter][1] == 'VIDEO': output = net_connect.send_command( 'sh call history video brief | i :') logfile.write(output) net_connect.disconnect() logfile.close() #CALL-SIP/CALL-PRI #VIDEO-SIP/VIDEO-PRI
# Code so automated tests will run properly password = (os.getenv("NETMIKO_PASSWORD") if os.getenv("NETMIKO_PASSWORD") else getpass()) cisco3 = { "device_type": "cisco_ios", "host": "cisco3.lasthop.io", "username": "******", "password": password, } # Connect to Cisco3 using Netmiko print() print(f"Connecting to: {cisco3['host']}") net_connect = ConnectHandler(**cisco3) # Ensure connected to cisco3 prompt = net_connect.find_prompt() if debug: print(f"\nCurrent prompt: {prompt}") if "cisco3" not in prompt: raise ValueError(f"Expecting 'cisco3' in prompt: {prompt}") if "CiscoIosSSH" not in str(net_connect): raise ValueError( f"Expecting CiscoIosSSH class at this point: {str(net_connect)}") print(f"Current class: {str(net_connect)}") # SSH to Arista4 from Cisco3 print("\nSSH from Cisco3 to Arista4:") output = net_connect.send_command(ssh_cmd,
import os import time from netmiko import ConnectHandler os.system("clear") time.sleep(1) host = raw_input("Enter Host IP: ") username = raw_input("Enter username: "******"Enter password: "******"Enter Command: ") platform = 'cisco_ios' device = ConnectHandler(device_type=platform, ip=host, username=username, password=password) output = device.send_command(command_input) print output
def respaldo_ssh_manual(hostname, ip, cisco_os, username, password, enable_password): try: ruta = os.getcwd() with open( ruta + "/full backup manual/respaldo_" + hostname + "_" + datetime.now().strftime("%d%m%Y_%H%M"), "w") as file: if cisco_os == "nxos": nx_node = { 'device_type': 'cisco_nxos', 'ip': ip, 'username': username, 'password': password, 'secret': enable_password, 'port': 22, } ssh_session = SSHSession(ip, username, password=password).open() for comando in commands_nxos: resultado = ssh_session.run_cmd(comando) file.write(resultado.output) ssh_session.close() elif cisco_os == "iosxe": ssh_session = SSHSession(ip, username, password=password).open() for comando in commands_iosxe: resultado = ssh_session.run_cmd(comando) file.write(resultado.output) ssh_session.close() elif cisco_os == "junos": ssh_session = SSHSession(ip, username, password=password, timeout=10).open() for comando in commands_junos: resultado = ssh_session.run_cmd(comando) file.write(resultado.output) ssh_session.close() elif cisco_os == "ios": ios_node = { 'device_type': 'cisco_ios', 'ip': ip, 'username': username, 'password': password, 'secret': enable_password, 'port': 22, } net_connect_ios = ConnectHandler(**ios_node) net_connect_ios.enable() for comando in commands_ios: resultado = net_connect_ios.send_command( comando, strip_prompt=False, strip_command=False) file.write(resultado) elif cisco_os == "asa": asa_node = { 'device_type': 'cisco_asa', 'ip': ip, 'username': username, 'password': password, 'secret': enable_password, 'port': 22, } net_connect_asa = ConnectHandler(**asa_node) net_connect_asa.enable() for comando in commands_asa: resultado = net_connect_asa.send_command(comando) file.write(resultado) return ({"resultado": "equipo " + hostname + " OK"}) except Exception as e: return ("Error " + str(e)) return ("realizado")
import netmiko from netmiko import ConnectHandler from getpass import getpass USERNAME = input("What is your Username?") SECRET = getpass() # Open file with list of switches f = open("controllers.txt") for line in f: # need to fix, doesn't like (line) #print ("Getting running config") + str(line) # #left over from manually asking IP address #controller = input("What is IP address of the WLC?") CONTROLLER = line.strip() device = ConnectHandler(device_type="cisco_wlc_ssh", ip=CONTROLLER, username=USERNAME, password=SECRET) output1 = device.send_command("config paging disable") output2 = device.send_command("show running-config") save_file = open("Runconfig" + str(CONTROLLER) + ".txt", "w") save_file.write(output2) save_file.close() device.disconnect() print("complete")
from netmiko import ConnectHandler iosv_l2 = { 'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': '******', 'password': '******', 'secret' : 'password' } net_connect = ConnectHandler(**iosv_l2) #net_connect.find_prompt() output = net_connect.send_command('show ip int brief') print ((output)) config_commands = ['int loop 0', 'ip address 1.1.1.1 255.255.255.0'] output = net_connect.send_config_set(config_commands) print (output) for n in range (2,21): print("Creating VLAN " + str(n)) config_commands = ['vlan ' + str(n), 'name Python_VLAN ' + str(n)] output = net_connect.send_config_set(config_commands) print (output)
worksheet1.cell(1,1).value="VLAN-ID" worksheet1.cell(1,2).value="VLAN-NAME" worksheet1.cell(1,3).value="SVI-ADDRESS" worksheet1.cell(1,4).value="SUBNET-MASK" worksheet1.cell(1,5).value="COMMENT" # -----------Load Workbook/Worksheet----------- # -----------Connect Device----------- deviceConnection = { 'device_type': 'cisco_ios', 'host': '192.168.138.10', 'username': '******', 'password': '******', 'port': 22, 'secret': ''} connect = ConnectHandler(**deviceConnection) # -----------Connect Device----------- # -----------Interface Brief---------- interface_brief_output = connect.send_command("show ip interface brief") interface_parsed = parse_output(platform="cisco_ios", command="show ip interface brief", data=interface_brief_output) # -----------Interface Brief---------- # -----------L2/L3 Info Function---------- # def switchport(interface): # interfaces_switchport_output = connect.send_command("""show interfaces """ + interface + """ switchport""") # interfaces_switchport_parsed = parse_output(platform="cisco_ios", command="show interfaces switchport",
# Authored by Tiam Abderezai # The following script logs into a Cisco device and retrieves its serial number: import re # import regular expression module from netmiko import ConnectHandler # import netmiko module credentials = { 'device_type': 'cisco_ios', 'ip': '172.16.1.1', 'username': '******', 'password': '******' } connection = ConnectHandler(**credentials) output = connection.send_command('show inventory') regexoutput = re.search('FOC.*', output) print(regexoutput.group(0))
from netmiko import ( ConnectHandler, NetMikoAuthenticationException, NetMikoTimeoutException ) import json import re with open(r'devices.json', 'r') as in_file: devices = json.load(in_file) sw1 =sw2 = sw3 = fw1 = hq1 = br1 = '' try: sw1 = ConnectHandler(**devices['sw1']) print('Connect to sw1 successfull') except: print('Connection to sw1 failed!') try: sw2 = ConnectHandler(**devices['sw2']) print('Connect to sw2 successfull') except: print('Connection to sw2 failed!') try: sw3 = ConnectHandler(**devices['sw3']) print('Connect to sw3 successfull') except: print('Connection to sw3 failed!') try: