def main(): for device in rtr_list: rtr_conn = ConnectHandler(**device) prompt = rtr_conn.find_prompt() rtr_conn.config_mode() output = rtr_conn.send_config_from_file(config_file='4_8_cfg.txt') print output
def connect_net_device(**kwarg): net_connect = ConnectHandler(**kwarg) print "Current prompt: {}".format(net_connect.find_prompt()) show_run = net_connect.send_command("sh run") print "sh run output: \n\n{}".format(show_run) filename = net_connect.base_prompt + ".txt" save_file (filename , show_run)
def main(): print 'Username:'******'device_type':DEV_TYPE[i], 'ip':DEVICES[i], 'username':usern, 'password':passwd } print '>>>>>>>>>>>>> DEVICE: {} <<<<<<<<<<<<<<'.format(DEVICES[i]) # Initiating netmiko connection net_connect = ConnectHandler(**net_dev) resp = net_connect.find_prompt() print resp # Entering config mode, deploying commands and exiting config mode resp = net_connect.send_config_set(CONF_COMMANDS) print resp except Exception as e: print e exit(0)
def main(): username = '******' password = '******' pynet1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': username, 'password': password, 'port': 22, } pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': username, 'password': password, 'port': 8022, } juniper_srx = { 'device_type': 'juniper', 'ip': '50.76.53.27', 'username': username, 'password': password, 'secret': '', 'port': 9822, } pynet_rtr2 = ConnectHandler( **pynet2 ) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode() : print "We are in config mode for pynet rtr2" else: print "No config mode for pynet rtr2"
def main(): ''' Use Netmiko to change the logging buffer size (logging buffered <size>) and to disable console logging (no logging console) from a file on both pynet-rtr1 and pynet-rtr2 ''' ip_address = raw_input("Please enter IP address: ") password = getpass() pynet_rtr1['ip'] = ip_address pynet_rtr2['ip'] = ip_address pynet_rtr1['password'] = password pynet_rtr2['password'] = password #for each router load config from #file and print result for router in (pynet_rtr1, pynet_rtr2): ssh_conn = ConnectHandler(verbose=False, **router) ssh_conn.send_config_from_file('ex8_config.txt') output = ssh_conn.send_command('show run | in logging') print "\n>>> {}:{} \n".format(ssh_conn.ip, ssh_conn.port) print output print ">>>\n"
def main(): """Exercises using Netmiko""" # 99saturday sw1_pass = getpass("Enter switch password: "******"Current Prompt: " + net_connect.find_prompt() print "\nConfiguring VLAN" print "#" * 80 output = net_connect.send_config_set(cfg_commands) print output print "#" * 80 print print "\nConfiguring VLAN from file" print "#" * 80 output = net_connect.send_config_from_file("vlan_cfg.txt") print output print "#" * 80 print
def main(): rtr1_pass = getpass("Enter router password: "******"Enter switch password: "******"show version") show_run = sw_con.send_command("show run") save_file(sw_con.base_prompt + '-ver', show_ver) save_file(sw_con.base_prompt + '-run', show_run)
def show_version(a_device): '''Establish connection with Netmiko + 'show version' command.''' creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, port=a_device.port, ip=a_device.ip_address, username=creds.username, password=creds.password, secret='') print 'Establishing connection via Netmiko to all net devices ', '\n', remote_conn print 80 * '_' command_outp = remote_conn.send_command_expect('show version')
def main(): ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2 and juniper-srx' ''' ip_addr = raw_input("Enter IP Address: ") password = getpass() #Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['ip'] = ip_addr a_dict['password'] = password a_dict['verbose'] = False print "\nStart time: " +str(datetime.now()) for rtr in (pynet1, pynet2, juniper_srx): rtr = ConnectHandler(**rtr) output = rtr.send_command("show arp") print print '#' * 80 print "Device: {}:{}".format(rtr.ip, rtr.port) print print output print '#' * 80 print print "\nEnd time: " + str(datetime.now())
def main(): """ The main function """ django.setup() total_elapsed_time = 0 device_list = NetworkDevice.objects.all() for device in device_list: starttime = time.time() remote_connection = ConnectHandler(device_type=device.device_type, ip=device.ip_address, port=device.port, username=device.credentials.username, password=device.credentials.password) print '=' * 50 print device.device_name print '-' * 15 print remote_connection.send_command_expect('show version') finishtime = time.time() timedelta = finishtime - starttime total_elapsed_time = total_elapsed_time + timedelta print 'Retrieval duration: %.2f seconds' % round(timedelta, 2) print print '*' * 50 print 'Overall retrieval duration: %.2f seconds' % round(total_elapsed_time, 2) print '*' * 50
def main(): ''' Use Netmiko to change the logging buffer size on pynet-rtr2. ''' ip_addr = raw_input("Enter IP address: ") password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2): a_dict['ip'] = ip_addr a_dict['password'] = password a_dict['verbose'] = False # Loop through each router and issue config command via config_file for a_device in (pynet1, pynet2): net_connect = ConnectHandler(**a_device) net_connect.send_config_from_file(config_file='config_file.txt') output = net_connect.send_command("show run | i logging") print print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print
def main(): ''' Use Netmiko to change the logging buffer size on pynet-rtr2. ''' ip_addr = raw_input("Enter IP address: ") password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['ip'] = ip_addr a_dict['password'] = password a_dict['verbose'] = False net_connect = ConnectHandler(**pynet2) config_commands = ['logging buffered 20000'] net_connect.send_config_set(config_commands) output = net_connect.send_command("show run | i logging buffer") print print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print
def main(): django.setup() # Load device info and credentials into database ex1_link_obj_2_credentials.link_device_to_credentials() devices = NetworkDevice.objects.all() for a_device in devices: if a_device.device_name and a_device.credentials: start_time = datetime.now() creds = a_device.credentials username = creds.username password = creds.password remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=username, password=password, port=a_device.port, secret='') # Print out 'show version' output print print '#' * 80 print ("'show version' output for device: %s" % a_device.device_name) print '#' * 80 print remote_conn.send_command("show version") # Print out elapsed time print '#' * 80 print ("Elapsed time: " + str(datetime.now() - start_time)) print '#' * 80
def show_version(a_device): remote_conn=ConnectHandler(device_type=a_device.device_type,ip=a_device.ip_address,username=a_device.credentials.username,password=a_device.credentials.password,port=a_device.port,secret='') print '\n' print '#' * 80 print remote_conn.send_command("show version") print '#' * 80 print '\n'
def main(): ip_addr = raw_input("Enter IP address: ") password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['ip'] = ip_addr a_dict['password'] = password a_dict['verbose'] = False print "\nStart time: " + str(datetime.now()) for a_device in (pynet1, pynet2, juniper_srx): net_connect = ConnectHandler(**a_device) output = net_connect.send_command("show arp") print print '#' * 80 print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print '#' * 80 print print "\nEnd time: " + str(datetime.now())
def main(): device_list = [cisco_ios, cisco_xr, arista_veos] start_time = datetime.now() print for a_device in device_list: as_number = a_device.pop('as_number') net_connect = ConnectHandler(**a_device) net_connect.enable() print "{}: {}".format(net_connect.device_type, net_connect.find_prompt()) if check_bgp(net_connect): print "BGP currently configured" remove_bgp_config(net_connect, as_number=as_number) else: print "No BGP" # Check BGP is now gone if check_bgp(net_connect): raise ValueError("BGP configuration still detected") # Construct file_name based on device_type device_type = net_connect.device_type file_name = 'bgp_' + device_type.split("_ssh")[0] + '.txt' # Configure BGP output = configure_bgp(net_connect, file_name) print output print print "Time elapsed: {}\n".format(datetime.now() - start_time)
def main(): """Exercises using Netmiko""" rtr1_pass = getpass("Enter router password: "******"Enter switch password: "******"Current Prompt: " + net_connect.find_prompt() show_arp = net_connect.send_command("show arp") print print '#' * 80 print show_arp print '#' * 80 print show_run = net_connect.send_command("show run") filename = net_connect.base_prompt + ".txt" print "Save show run output: {}\n".format(filename) save_file(filename, show_run)
def main(): router1 = { 'device_type': 'cisco_ios', 'ip': '10.9.0.67', 'username': '******', 'password': '******' } router2 = { 'device_type': 'cisco_ios', 'ip': '10.63.176.57', 'username': '******', 'password': '******' } routers = [router1, router2] for router in routers: # Connect to device device_conn = ConnectHandler(**router) # Print arp table print device_conn.send_command("show arp") print "\n\n" # Close connection device_conn.disconnect()
def main(): for device in rtr_list: rtr_conn = ConnectHandler(**device) output = rtr_conn.send_command("show arp") print device['ip'], " ARP Table:\n" print "===========================================================" print output, "\n"
def main(): ip_addr = '50.76.53.27' port_rtr1 = 22 port_rtr2 = 8022 username = '******' password = '******' #password = getpass() pynet1 = { 'device_type': 'cisco_ios', 'ip': ip_addr, 'username': username, 'password': password, 'port': port_rtr1, } pynet2 = { 'device_type': 'cisco_ios', 'ip': ip_addr, 'username': username, 'password': password, 'port': port_rtr2, } pynet_rtr1 = ConnectHandler(**pynet1) pynet_rtr2 = ConnectHandler(**pynet2) out1 = pynet_rtr1.send_config_from_file(config_file='w4-8-commands.txt') out2 = pynet_rtr2.send_config_from_file(config_file='w4-8-commands.txt') print "The output in rtr1 is:\n%s\n" % out1 print "The output in rtr2 is:\n%s\n" % out2
def main(): """ Write a Python script that retrieves all of the network devices from the database Using this data, make a Netmiko connection to each device. Retrieve 'show run'. Record the time that the program takes to execute. """ start_time = datetime.now() django.setup() my_devices = NetworkDevice.objects.all() print for a_device in my_devices: a_device_netmiko = create_netmiko_dict(a_device) remote_conn = ConnectHandler(**a_device_netmiko) if 'juniper' in a_device.device_type: show_run = remote_conn.send_command_expect("show configuration") else: show_run = remote_conn.send_command_expect("show run") print a_device.device_name print '-' * 80 print show_run print '-' * 80 print print ">>>>>>>> Total Time: {}".format(datetime.now() - start_time) print
def main(): django.setup() start_time = datetime.now() devices = NetworkDevice.objects.all() credentials = Credentials.objects.all() for a_device in devices: print "\n", a_device device_type = a_device.device_type port = a_device.port secret = '' ip = a_device.ip_address creds = a_device.credentials username = creds.username password = creds.password remote_conn = ConnectHandler(device_type=device_type, ip=ip, username=username, password=password, port=port, secret=secret) print "#" * 50 print remote_conn.send_command("show arp") print "#" * 50 pass elapsed_time = datetime.now() - start_time print "Elapsed time: {}".format(elapsed_time)
def main(): ''' Use Netmiko to change the logging buffer size and to disable console logging from a file for both pynet-rtr1 and pynet-rtr2 ''' ip_addr = raw_input("Enter IP address: ") password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['ip'] = ip_addr a_dict['password'] = password a_dict['verbose'] = False for a_device in (pynet1, pynet2): net_connect = ConnectHandler(**a_device) net_connect.send_config_from_file(config_file='config_file.txt') # Verify configuration output = net_connect.send_command("show run | inc logging") print print '#' * 80 print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print '#' * 80 print
def main(): ''' Use Netmiko to connect to each of the devices in the database. Execute 'show version' on each device. Calculate the amount of time required to do this. ''' django.setup() devices = NetworkDevice.objects.all() start_time = datetime.now() for a_device in devices: creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='') print print a_device print '#' * 80 print remote_conn.send_command_expect("show version") print '#' * 80 print elapsed_time = datetime.now() - start_time print "Elapsed time: {}".format(elapsed_time)
def main(): #password = getpass() password = '******' # Define libraries for devices we will connect to pynet1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 22, } pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } srx = { 'device_type': 'juniper', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 9822, } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() outp = pynet_rtr2.find_prompt() print outp outp2 = pynet_rtr2.check_config_mode() print 'Config mode status is ' + str(outp2)
def main(): try: hostname = raw_input("Enter remote host to test: ") except NameError: hostname = input("Enter remote host to test: ") home_dir = path.expanduser("~") key_file = "{}/.ssh/cisco_rsa".format(home_dir) cisco_test = { "ip": hostname, "username": "******", "device_type": "cisco_ios", "use_keys": True, "key_file": key_file, "verbose": False, } net_connect = ConnectHandler(**cisco_test) print() print("Checking prompt: ") print(net_connect.find_prompt()) print() print("Testing show ip int brief: ") output = net_connect.send_command("show ip int brief") print(output) print()
def show_version(a_device): """Execute show version command using Netmiko.""" remote_conn = ConnectHandler(**a_device) print() print("#" * 80) print(remote_conn.send_command("show version")) print("#" * 80) print()
def show_version(a_device): '''Execute show version command using Netmiko.''' remote_conn = ConnectHandler(**a_device) print() print('#' * 80) print(remote_conn.send_command("show version")) print('#' * 80) print()
def show_version(dev): print "#"*30 + " " + dev.device_name + " " + "#" * 30 conn = ConnectHandler(device_type=dev.device_type, ip=dev.ip_address, username=dev.credentials.username, password=dev.credentials.password, port=dev.port) print conn.send_command_expect('show version') print "#" * 80 print
# Array of routers as defined above devices = [SR1, SR2, AGG1, AGG2, PAG1, PAG2, CSG1, CSG2, XTC, VRR] for device in devices: try: labRouter = { 'device_type': 'cisco_ios', 'ip': device.inputIpAddr, 'username': device.inputUser, 'password': device.inputPassword, 'port': PORT_NUMBER, # 'secret': '%', # Add secret password, if any 'verbose': True } connectRouter = ConnectHandler(**labRouter) prompt = connectRouter.find_prompt() print(prompt) print('Entering Privileged EXEC mode...') connectRouter.enable() fileName = device.inputHostName + '.cfg' # or '.txt', depending on file format commmandList = connectRouter.send_config_from_file(fileName) print(commmandList) connectRouter.disconnect() print('Connection to ' + device.inputHostName + ' is now closed.')
iosv_l2_s5 = { 'device_type': 'cisco_ios', 'ip': '192.168.122.75', 'username': '******', 'password': '******', } with open('iosv_l2_cisco_design' ) as f: #open file which contains all required configurations lines = f.read().splitlines() print lines all_devices = [iosv_l2_s5, iosv_l2_s4, iosv_l2_s3] for devices in all_devices: net_connect = ConnectHandler(**devices) output = net_connect.send_config_set( lines) #configuring the access layer switches print output with open('iosv_l2_core') as f: lines = f.read().splitlines() #configuring core layer switches print lines all_devices = [iosv_l2_s2, iosv_l2_s1] for devices in all_devices: net_connect = ConnectHandler(**devices) output = net_connect.send_config_set(lines) print output
with open('H:\Scripts\Logging Script\devices') as f: devices_list = f.read().splitlines() for devices in devices_list: print('Connecting to device" ' + devices) ip_address_of_device = devices ios_device = { 'device_type': 'cisco_ios', 'ip': ip_address_of_device, 'username': username, 'password': password } try: net_connect = ConnectHandler(**ios_device) except (AuthenticationException): print('Authentication failure: ' + ip_address_of_device) with open("H:\Scripts\Logging Script\error.log", "a") as e: e.write("script " + scriptname + " User " + username + " " + time_stamp() + " " + ip_address_of_device + " Wrong credentials.\n") e.close() continue except (NetMikoTimeoutException): print('Timeout to device: ' + ip_address_of_device) with open("H:\Scripts\Logging Script\error.log", "a") as e: e.write("script " + scriptname + " User " + username + " " + time_stamp() + " " + ip_address_of_device + " Timeout connecting to the device.\n") e.close()
def config_worker(CONFIG_PARAMS_LIST): IP_ADDRESS_DEVICE = CONFIG_PARAMS_LIST[0] USERNAME = CONFIG_PARAMS_LIST[1] PASSWORD = CONFIG_PARAMS_LIST[2] ios_devices = { "device_type": "cisco_ios", "ip": IP_ADDRESS_DEVICE, "username": USERNAME, "password": PASSWORD } for i in range(1, 2): try: net_connect = ConnectHandler(**ios_devices) except (AuthenticationException): print("**** Error: Authentication failure: " + IP_ADDRESS_DEVICE + " ****") continue except (NetMikoTimeoutException): print("**** Error: Timeout to device: " + IP_ADDRESS_DEVICE + " ****") continue except (EOFError): print("**** Error: End of file while attempting device: " + IP_ADDRESS_DEVICE + " ****") continue except (SSHException): print("**** Error: SSH Issue. Are you sure SSH is enabled?: " + IP_ADDRESS_DEVICE + " ****") continue except Exception as unknown_error: print("**** Error: Some other error " + IP_ADDRESS_DEVICE + " ****") continue #get hostname net_connect.send_config_set("terminal length 0") output_hostname = net_connect.send_command("show run | i hostname") output_hostname = output_hostname.replace("\r", "").replace("\n", "").split(" ") hostname = (output_hostname[1]) #get interface output_interface = net_connect.send_command("show ip interface brief") intf_pattern = "^[lLgGeEfF]\S+[0-9]/?[0-9]*" regex = re.compile(intf_pattern) for row in output_interface.splitlines(): if regex.search(row): INTERFACE = row.split()[0] STATUS = row.split()[4] PROTOCOL = row.split()[5] if "up" == STATUS: output_interface_config = net_connect.send_command( "show running-config interface " + INTERFACE) interface_config = output_interface_config.find( "negotiation auto") if interface_config > 0: negotiation = ("OK") else: negotiation = ("NOK") interface_config = output_interface_config.find( "speed auto") if interface_config > 0: speed = ("OK") else: speed = ("NOK") interface_config = output_interface_config.find( "duplex auto") if interface_config > 0: duplex = ("OK") else: duplex = ("NOK") if INTERFACE.find("Loop") < 0: if negotiation == ("NOK") and speed == ( "NOK") and duplex == ("NOK"): print(hostname + " " + INTERFACE + " no auto port") elif negotiation == ("NOK") and speed == ( "NOK") or duplex == ("NOK"): print(hostname + " " + INTERFACE + " Speed or duplex wrong") net_connect.disconnect() return
class MainFrame(): def __init__(self): self.root = tk.Tk() self.root.title('DmVpn Constructor Application') self.style = ttk.Style() self.style.configure('TFrame', background='#e1d8a1') self.style.configure('TButton', background='#b1d8b9') self.style.configure('TLabel', background='#e1d8b1', font=('Arial', 10, 'bold')) self.style.configure('Header.TLabel', background='#e1d8b9', font=('Arial', 15, 'bold')) self.panedwindow = ttk.PanedWindow(self.root, orient=tk.VERTICAL) self.panedwindow.pack() self.frame_header = ttk.Frame(self.panedwindow, width=500, height=100, relief=tk.SUNKEN) self.frame_body = ttk.Frame(self.panedwindow, width=500, height=300) self.panedwindow.add(self.frame_header, weight=1) self.panedwindow.add(self.frame_body, weight=4) self.logo = tk.PhotoImage(file='') ttk.Label(self.frame_header, image=self.logo).grid(row=0, column=0, rowspan=2) ttk.Label(self.frame_header, wraplength=100, text='Input Fields', font=('Arial', 11, 'bold')).grid(row=0, column=1, columnspan=2, sticky='s') ttk.Label(self.frame_header, text='Hub Ip Address').grid(row=1, column=0, sticky='s') ttk.Label(self.frame_header, text='Spoke Ip Address').grid(row=1, column=3, sticky='e', padx=8) self.hub_entry = ttk.Entry(self.frame_header, width=15) self.hub_entry.grid(row=2, column=0, padx=15, pady=(2, 7)) self.spoke_entry = ttk.Entry(self.frame_header, width=15) self.spoke_entry.grid(row=2, column=3, sticky='e', padx=7, pady=(2, 7)) self.txtvar = tk.StringVar() self.txtvar.set('Please Input Hub & Spoke Ip Addresses') self.message = tk.Message(self.frame_body, width=350, bd=10, bg='#e1d8a1', relief=tk.RIDGE, textvariable=self.txtvar, font=('Arial', 12, 'bold')) self.message.grid(row=1, columnspan=2, padx=10, pady=5) self.clear_button = ttk.Button(self.frame_body, text='Clear', command=self.clear_entry) self.clear_button.grid(row=2, column=1, padx=5, pady=(12, 5), sticky='w') self.submit_button = ttk.Button(self.frame_body, text='Submit', command=self.submit_ip) self.submit_button.grid(row=2, column=0, padx=5, pady=(12, 5), sticky='e') self.root.bind('<Escape>', func=self.destroy_self) self.root.bind("<Return>", func=self.submit_ip) self.root.bind("<KP_Enter>", func=self.submit_ip) self.root.mainloop() @staticmethod # function to check ip address sanity def check_ip(ip): try: ipaddress.ip_address(ip) return True except ValueError as err: tk.messagebox.showerror(title="Input Error", message=err) return False def pingable(self, ip): # function to check device reachability self.retry = None try: result = subprocess.call(["ping", "-c 1", ip], stdout=subprocess.PIPE) if result == 1: tk.messagebox.showinfo( message=f"Device {ip} is unreachable !!!") except SubprocessError as err: tk.messagebox.showinfo(message=err) return result def destroy_self(self, event=None): self.root.destroy() def clear_entry(self): self.hub_entry.delete(0, 'end') self.spoke_entry.delete(0, 'end') def submit_ip( self, event=None ): # this function defines behavier when "submit_ip" button is pressed try: global Hub_Ip, Spoke_Ip Hub_Ip = self.hub_entry.get() # read Hub ip address Spoke_Ip = self.spoke_entry.get() # read Spoke ip address if (self.check_ip(Hub_Ip) == False) or ( self.check_ip(Spoke_Ip) == False): # Check for HUB and Spoke ip address sanity self.clear_entry() self.txtvar.set("Please Try Again. Input the correct Ip's") elif Hub_Ip == Spoke_Ip: self.clear_entry() self.txtvar.set("Please Try Again. Same Ip's not allowed") else: self.clear_entry() self.txtvar.set("Ip's are accepted. Starting application ...") self.main_foo() except AttributeError as err: # exception when attribute is not found in class object print("Error in program execution !!!", '\n', err) except paramiko.buffered_pipe.PipeTimeout as err: # catch timeout exception print(err) except NetMikoTimeoutException as err: print(err) except OSError as err: print("Error in Netmiko Module !!!", '\n', err) return Hub_Ip, Spoke_Ip def main_foo(self): COUNT = 0 global flag flag = True key_list = ['device_type', 'ip', 'username', 'password'] listglobal = ['cisco_ios', 'elil', 'cisco'] listglobal.insert(1, Hub_Ip) listglobal1 = ['cisco_ios', 'elil', 'cisco'] listglobal1.insert(1, Spoke_Ip) device1 = dict(zip( key_list, listglobal)) # define dictionary for Netmiko (**kwarg ) device2 = dict(zip(key_list, listglobal1)) devices = [device1, device2] result = tk.messagebox.askyesno( message="Ip's are Accepted\n Continue?") if result == False: # exit program if "No" button pressed self.message.grid(row=1, columnspan=2, padx=80, pady=5) self.txtvar.set(' Exiting application ..') self.root.after(2000, self.root.destroy) for device in devices: # check connectivity to devices reachable = self.pingable(device["ip"]) COUNT += reachable if COUNT == 0: # if all devices are pingable then proceed self.config_collector(devices, COMMAND_LIST) # collects data from devices for item in value_list: if 'Invalid' in item: # if got an output error ... tk.messagebox.showerror( title="Fatal Error", message= "Wrong commands executed..\n terminating programm !!!") self.destroy_self() sys.exit() elif (len(item) == 0 ): # if could not get proper configuration ... flag = False self.config_collector( devices, COMMAND_LIST) # then recollect data from devices else: flag = True self.config_parser() # parse configuration spoke_jinja_cfg = Files_Constructor( r'/home/elil/Yml/SPOKE_DICT.yml') # Instantiate Class hub_jinja_cfg = Files_Constructor( r'/home/elil/Yml/HUB_DICT.yml') # Instantiate Class spoke_jinja_cfg.create_yaml_file( bgp_dict, 'w') # Configuring YAML file for Spoke spoke_jinja_cfg.create_yaml_file( spoke_dict, 'a') # Configuring YAML file for Spoke hub_jinja_cfg.create_yaml_file( hub_dict, 'w') # Configuring YAML file for Hub self.result1 = spoke_jinja_cfg.constructor( r"/home/elil/Templates/", r'child_spoke_config.j2') self.result2 = hub_jinja_cfg.constructor(r"/home/elil/Templates/", r'hub_config.j2') self.cfg_compile() # finalizing configuration of devices pdb.set_trace() threads_conn(send_config, devices, 2, self.cfg_list) # send configuration to devices proceed = messagebox.askyesno( message= 'Spoke device is added to DmVpn cloud. Would you like to configure next device ?' ) if proceed == True: self.root.lift() self.root.focus_force() self.clear_entry() self.txtvar.set('Please Input Hub & Spoke Ip Addresses') else: self.root.destroy() else: # if one of the devices are unreachable then proceed .. self.clear_entry() self.retry = tk.messagebox.askretrycancel( message="Retry? Quit Application?") if self.retry == True: # if pressed "retry" button self.clear_entry() # clear input self.txtvar.set("Check devices reachability before input") else: # if pressed "cancel" button self.root.destroy() # terminate programm return Hub_Ip, Spoke_Ip, flag def netmiko_ssh(self, args): # main function for ssh connection self.ssh = ConnectHandler(**args) def send_show(command): return self.ssh.send_command(command) return send_show def config_collector(self, params, commands): # funtion collects cfg data from devices self.root.iconify() global mq_dict, value_list queue = Queue() for device, command in zip(params, commands): try: if flag == True: self.result = tk.messagebox.askokcancel( message= f'Procced with connection to device {device["ip"]} ?') else: self.result = tk.messagebox.askokcancel( message= f'ReCollect device {device["ip"]} configuration ?') if self.result == False: # exit program if "Cancel" button pressed self.root.destroy() Session = self.netmiko_ssh(device) # connects to device if type(command) == str: queue.put(Session(command)) # gets device configuration else: for cfg in command: queue.put( Session(cfg)) # add device output to the queue except NetMikoAuthenticationException as err: tk.messagebox.showerror(message=err) except NetMikoTimeoutException as err: tk.messagebox.showerror(message=err) mq_dict = {} # zeroize dictionary value_list = [] key_list = ['hub_bgp_list', 'sir_str', 'sib_str', 'hostname'] try: while not queue.empty(): value_list.append( queue.get(timeout=2)) # get data from the queue except queue.Empty as err: print(err) mq_dict = dict(zip(key_list, value_list)) # configure intermediate dict return mq_dict, value_list def config_parser(self): global hub_dict, spoke_dict, bgp_dict # define global variables for Yaml file bgp_neigbors = [] # list of Hub current BGP Neigbors bgp_dict = {'bgp': bgp_neigbors} # Bgp neigbors dictionary(For Yaml) for key, value in mq_dict.items(): globals().update(mq_dict) ''' Get Data from Hub Configuration and create Yaml File ''' ([ bgp_neigbors.append(line) for line in mq_dict['hub_bgp_list'].splitlines() if ('neighbor' and 'remote-as') in line ]) ''' Get Data from Spoke Configuration and create dictionary for Yaml File ''' for line in sib_str.splitlines()[1:]: iface, ip, *_, status, proto = line.split() if (ip != 'unassigned' and (status and proto == 'up')): if not (iface.startswith('L') or iface.startswith('T')): tunnel_ip = ip.replace('10.1', '10.2', 1) # Gre Tunnel ip address asn = int(ip[5:6]) * 10 interface = iface # get source interface for Gre Tunnel else: if not iface.startswith('T'): network = ip # get local network to advertise through BGP for line in sir_str.splitlines(): if line.startswith('S*'): *junk, nexthop = line.split() # extract nexthop ip address spoke_network_prefix = ipaddress.ip_network( Spoke_Ip + '/30', strict=False) # get network address from "Spoke_Ip" row_network = re.match("(\S+)/", spoke_network_prefix.with_prefixlen ) # get network address from "Spoke_Ip" spoke_subnet = row_network.group( 1) # get network address from "Spoke_Ip" ''' Create Spoke router's dictionary for Yaml File ''' spoke_dict = { 'description': 'To_HUB', 'hostname': hostname.split()[1], 'tunnel_ip': tunnel_ip, 'network': network, 'as_number': asn, 'interface': interface, 'nexthop': nexthop } ''' Create Hub router's dictionary for Yaml File ''' hub_dict = { 'spoke_subnet': spoke_subnet, 'tunnel_ip': tunnel_ip, 'as_number': asn } tk.messagebox.showinfo(message='Finalizing configuration ...') return spoke_dict, hub_dict, bgp_dict def cfg_compile(self): global spoke_cfg global hub_cfg spoke_cfg = [] # define final config list for Spoke hub_cfg = [] # define final config list for Hub [spoke_cfg.append(line) for line in self.result1.splitlines()] # Spoke final configuration [hub_cfg.append(line) for line in self.result2.splitlines()] # Hub final configuration self.cfg_list = [hub_cfg, spoke_cfg] return self.cfg_list, spoke_cfg, hub_cfg
def __init__(self, host_addr, type, uname, pwd): self.connect = ConnectHandler(device_type=type, ip=host_addr, username=uname, password=pwd) self.password = pwd
# Define devices variable devices = [] for ip in device_ip_list: devices.append({ "device_type": "cisco_ios", # must be the same for all devices "ip": ip, # IP of each device from the Excel file "username": "******", # must be the same for all devices "password": "******", # must be the same for all devices "port": 22, # must be the same for all devices # If port for all devices is not 22 you will get an error "fast_cli": False, }) for device in devices: # Create a connection instance with try/except block to handle connection errors try: with ConnectHandler(**device) as net_connect: # hostname of the current device hostname = net_connect.send_command( command_sting="show version", use_textfsm=True)[0]["hostname"] run_cfg: str = net_connect.send_command( command_sting="show running-config") # Create .txt for each running configuration of each device with open(file=f"{hostname}_ex7-run-cfg.txt", mode="w") as outfile: outfile.write(run_cfg.lstrip()) except Exception as e: # Handle any exception raise SystemExit(e) print("Done")
from netmiko import ConnectHandler device_information = { 'device_type': 'cisco_ios', 'host': '192.168.128.100', 'username': input("Enter your username : "******"Enter your password : "******" *** Creating VLAN : " + str(n)) config_vlans = ['Vlan ' + str(n), 'name Emir ' + str(n)] send_commands = connect.send_config_set(config_vlans, cmd_verify=False) print(send_commands) connect.disconnect()
pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': password, } juniper_srx = { 'device_type': 'juniper', 'ip': '184.105.247.76', 'username': '******', 'password': password, 'secret': '', } pynet_rtr1 = ConnectHandler(**pynet1) #pynet_rtr2 = ConnectHandler(**pynet2) #srx = ConnectHandler(**juniper_srx) # Print router prompt print pynet_rtr1.find_prompt() # Enter configuration mode pynet_rtr1.config_mode() # Check that router is in configuration mode print pynet_rtr1.check_config_mode() print pynet_rtr1.find_prompt() # Exit out of config mode and confirm pynet_rtr1.exit_config_mode()
print("Valid Ip address") else: print("Invalid Ip address") if __name__ == '__main__': Ip = input("Enter your IP address:") check(Ip) cisco_device123 = { "device_type": "cisco_ios", "ip": Ip, "username": "******", "password": "******", "port": 22 } net_connect123 = ConnectHandler(**cisco_device123) var = 1 while var == 1: interface123 = input("enter the interface you want to enable:") output123 = net_connect123.send_command("show ip int " + interface123) if 'Invalid input detected' in output123: print('You entered and invalid interface') else: first_line123 = output123.splitlines()[0] print(first_line123) if not "up" in first_line123: print("Interface is down, enabling this interface...") commands = ["interface " + interface123, "no shutdown", "exit"] output123 = net_connect123.send_config_set(commands)
class CEDriver(NetworkDriver): """Napalm driver for HUAWEI CloudEngine.""" def __init__(self, hostname, username, password, timeout=60, optional_args=None): """NAPALM Huawei CloudEngine Handler.""" self.device = None self.hostname = hostname self.username = username self.password = password self.timeout = timeout # Get optional arguments if optional_args is None: optional_args = {} # Netmiko possible arguments netmiko_argument_map = { 'port': None, 'verbose': False, 'timeout': self.timeout, 'global_delay_factor': 1, 'use_keys': False, 'key_file': None, 'ssh_strict': False, 'system_host_keys': False, 'alt_host_keys': False, 'alt_key_file': '', 'ssh_config_file': None, 'allow_agent': False, 'keepalive': 30 } # Build dict of any optional Netmiko args self.netmiko_optional_args = { k: optional_args.get(k, v) for k, v in netmiko_argument_map.items() } self.transport = optional_args.get('transport', 'ssh') self.port = optional_args.get('port', 22) self.changed = False self.loaded = False self.backup_file = '' self.replace = False self.merge_candidate = '' self.replace_file = '' self.profile = ["ce"] def open(self): """Open a connection to the device.""" try: if self.transport == 'ssh': device_type = 'huawei' else: raise ConnectionException("Unknown transport: {}".format( self.transport)) self.device = ConnectHandler(device_type=device_type, host=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) # self.device.enable() except NetMikoTimeoutException: raise ConnectionException('Cannot connect to {}'.format( self.hostname)) def close(self): """Close the connection to the device.""" if self.changed and self.backup_file != "": self._delete_file(self.backup_file) self.device.disconnect() self.device = None def is_alive(self): """Return a flag with the state of the SSH connection.""" null = chr(0) try: if self.device is None: return {'is_alive': False} else: # Try sending ASCII null byte to maintain the connection alive self.device.send_command(null) except (socket.error, EOFError): # If unable to send, we can tell for sure that the connection is unusable, # hence return False. return {'is_alive': False} return {'is_alive': self.device.remote_conn.transport.is_active()} def compare_config(self): """Compare candidate config with running.""" if self.loaded: if not self.replace: return self._get_merge_diff() # return self.merge_candidate diff = self._get_diff(self.replace_file.split('/')[-1]) return diff return '' def discard_config(self): """Discard changes.""" if self.loaded: self.merge_candidate = '' # clear the buffer if self.loaded and self.replace: self._delete_file(self.replace_file) self.loaded = False def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Huawei' uptime = -1 serial_number, fqdn, os_version, hostname, model = (u'Unknown', u'Unknown', u'Unknown', u'Unknown', u'Unknown') # obtain output from device show_ver = self.device.send_command('display version') show_hostname = self.device.send_command( 'display current-configuration | inc sysname') show_int_status = self.device.send_command('display interface brief') # serial_number/IOS version/uptime/model for line in show_ver.splitlines(): if 'VRP (R) software' in line: search_result = re.search( r"\((?P<serial_number>CE\S+)\s+(?P<os_version>V\S+)\)", line) if search_result is not None: serial_number = search_result.group('serial_number') os_version = search_result.group('os_version') if 'HUAWEI' in line and 'uptime is' in line: search_result = re.search(r"CE\S+", line) if search_result is not None: model = search_result.group(0) uptime = self._parse_uptime(line) break if 'sysname ' in show_hostname: _, hostname = show_hostname.split("sysname ") hostname = hostname.strip() # interface_list filter interface_list = [] if 'Interface' in show_int_status: _, interface_part = show_int_status.split("Interface") re_intf = r"(?P<interface>\S+)\s+(?P<physical_state>down|up|offline|\*down)\s+" \ r"(?P<protocal_state>down|up|\*down)" search_result = re.findall(re_intf, interface_part, flags=re.M) for interface_info in search_result: interface_list.append(interface_info[0]) return { 'uptime': int(uptime), 'vendor': vendor, 'os_version': str(os_version), 'serial_number': str(serial_number), 'model': str(model), 'hostname': str(hostname), 'fqdn': fqdn, # ? fqdn(fully qualified domain name) 'interface_list': interface_list } def cli(self, commands): """Execute raw CLI commands and returns their output.""" cli_output = {} if type(commands) is not list: raise TypeError('Please enter a valid list of commands!') for command in commands: output = self.device.send_command(command) cli_output[str(command)] = output return cli_output def commit_config(self): """Commit configuration.""" if self.loaded: try: self.backup_file = 'config_' + datetime.now().strftime( "%Y%m%d_%H%M") + '.cfg' if self._check_file_exists(self.backup_file): self._delete_file(self.backup_file) self._save_config(self.backup_file) if self.replace: self._load_config(self.replace_file.split('/')[-1]) else: self._commit_merge() self.merge_candidate = '' # clear the merge buffer self.changed = True self.loaded = False self._save_config() except Exception as e: raise CommitError(str(e)) else: raise CommitError('No config loaded.') def load_merge_candidate(self, filename=None, config=None): """Open the candidate config and merge.""" if not filename and not config: raise MergeConfigException( 'filename or config param must be provided.') self.merge_candidate += '\n' # insert one extra line if filename is not None: with open(filename, "r") as f: self.merge_candidate += f.read() else: self.merge_candidate += config self.replace = False self.loaded = True def load_replace_candidate(self, filename=None, config=None): """Open the candidate config and replace.""" if not filename and not config: raise ReplaceConfigException( 'filename or config param must be provided.') self._replace_candidate(filename, config) self.replace = True self.loaded = True def get_interfaces(self): """ Get interface details (last_flapped is not implemented). Sample Output: { "Vlanif3000": { "is_enabled": false, "description": "", "last_flapped": -1.0, "is_up": false, "mac_address": "0C:45:BA:7D:83:E6", "speed": 1000, 'mtu': 1500 }, "Vlanif100": { "is_enabled": false, "description": "", "last_flapped": -1.0, "is_up": false, "mac_address": "0C:45:BA:7D:83:E4", "speed": 1000, 'mtu': 1500 } } """ interfaces = {} output = self.device.send_command('display interface') if not output: return {} separator = r"(^(?!Line protocol).*current state.*$)" re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$" re_protocol = r"Line protocol current state\W+(?P<protocol>.+)$" re_mac = r"Hardware address is\W+(?P<mac_address>\S+)" re_speed = r"^Speed\W+(?P<speed>\d+|\w+)" re_description = r"^Description:(?P<description>.*)$" re_mtu = r"(Maximum Transmit Unit|Maximum Frame Length) is (?P<mtu>\d+)" new_interfaces = self._separate_section(separator, output) for interface in new_interfaces: interface = interface.strip() match_intf = re.search(re_intf_name_state, interface, flags=re.M) match_proto = re.search(re_protocol, interface, flags=re.M) if match_intf is None or match_proto is None: msg = "Unexpected interface format: {}".format(interface) raise ValueError(msg) intf_name = match_intf.group('intf_name') intf_state = match_intf.group('intf_state') is_enabled = bool('up' in intf_state.lower()) protocol = match_proto.group('protocol') is_up = bool('up' in protocol.lower()) match_mac = re.search(re_mac, interface, flags=re.M) if match_mac: mac_address = match_mac.group('mac_address') mac_address = napalm.base.helpers.mac(mac_address) else: mac_address = "" speed = mtu = 0 match_speed = re.search(re_speed, interface, flags=re.M) if match_speed: speed = match_speed.group('speed') if speed.isdigit(): speed = int(speed) match_mtu = re.search(re_mtu, interface, flags=re.M) if match_mtu: mtu = match_mtu.group('mtu') if mtu.isdigit(): mtu = int(mtu) description = '' match = re.search(re_description, interface, flags=re.M) if match: description = match.group('description').strip() interfaces.update({ intf_name: { 'description': description, 'is_enabled': is_enabled, 'is_up': is_up, 'last_flapped': -1.0, 'mac_address': mac_address, 'speed': speed, 'mtu': mtu } }) return interfaces def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "LoopBack0": { "ipv4": { "192.168.0.9": { "prefix_length": 32 } } }, "Vlanif2000": { "ipv4": { "192.168.200.3": { "prefix_length": 24 }, "192.168.200.6": { "prefix_length": 24 }, "192.168.200.8": { "prefix_length": 24 } }, "ipv6": { "FC00::1": { "prefix_length": 64 } } } } """ interfaces_ip = {} output_v4 = self.device.send_command('display ip interface') output_v6 = self.device.send_command('display ipv6 interface') v4_interfaces = {} separator = r"(^(?!Line protocol).*current state.*$)" new_v4_interfaces = self._separate_section(separator, output_v4) for interface in new_v4_interfaces: re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$" re_intf_ip = r"Internet Address is\s+(?P<ip_address>\d+.\d+.\d+.\d+)\/(?P<prefix_length>\d+)" match_intf = re.search(re_intf_name_state, interface, flags=re.M) if match_intf is None: msg = "Unexpected interface format: {}".format(interface) raise ValueError(msg) intf_name = match_intf.group('intf_name') # v4_interfaces[intf_name] = {} match_ip = re.findall(re_intf_ip, interface, flags=re.M) for ip_info in match_ip: val = {'prefix_length': int(ip_info[1])} # v4_interfaces[intf_name][ip_info[0]] = val v4_interfaces.setdefault(intf_name, {})[ip_info[0]] = val v6_interfaces = {} separator = r"(^(?!IPv6 protocol).*current state.*$)" new_v6_interfaces = self._separate_section(separator, output_v6) for interface in new_v6_interfaces: re_intf_name_state = r"^(?!IPv6 protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$" re_intf_ip = r"(?P<ip_address>\S+), subnet is.+\/(?P<prefix_length>\d+)" match_intf = re.search(re_intf_name_state, interface, flags=re.M) if match_intf is None: msg = "Unexpected interface format: {}".format(interface) raise ValueError(msg) intf_name = match_intf.group('intf_name') match_ip = re.findall(re_intf_ip, interface, flags=re.M) for ip_info in match_ip: val = {'prefix_length': int(ip_info[1])} v6_interfaces.setdefault(intf_name, {})[ip_info[0]] = val # Join data from intermediate dictionaries. for interface, data in v4_interfaces.items(): interfaces_ip.setdefault(interface, {'ipv4': {}})['ipv4'] = data for interface, data in v6_interfaces.items(): interfaces_ip.setdefault(interface, {'ipv6': {}})['ipv6'] = data return interfaces_ip def get_interfaces_counters(self): """Return interfaces counters.""" def process_counts(tup): for item in tup: if item != "": return int(item) return 0 interfaces = {} # command "display interface counters" lacks of some keys output = self.device.send_command('display interface') if not output: return {} separator = r"(^(?!Line protocol).*current state.*$)" re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$" re_unicast = r"Unicast:\s+(\d+)|(\d+)\s+unicast" re_multicast = r"Multicast:\s+(\d+)|(\d+)\s+multicast" re_broadcast = r"Broadcast:\s+(\d+)|(\d+)\s+broadcast" re_dicards = r"Discard:\s+(\d+)|(\d+)\s+discard" re_rx_octets = r"Input.+\s+(\d+)\sbytes|Input:.+,(\d+)\sbytes" re_tx_octets = r"Output.+\s+(\d+)\sbytes|Output:.+,(\d+)\sbytes" re_errors = r"Total Error:\s+(\d+)|(\d+)\s+errors" new_interfaces = self._separate_section(separator, output) for interface in new_interfaces: interface = interface.strip() match_intf = re.search(re_intf_name_state, interface, flags=re.M) if match_intf is None: msg = "Unexpected interface format: {}".format(interface) raise ValueError(msg) intf_name = match_intf.group('intf_name') intf_counter = { 'tx_errors': 0, 'rx_errors': 0, 'tx_discards': 0, 'rx_discards': 0, 'tx_octets': 0, 'rx_octets': 0, 'tx_unicast_packets': 0, 'rx_unicast_packets': 0, 'tx_multicast_packets': 0, 'rx_multicast_packets': 0, 'tx_broadcast_packets': 0, 'rx_broadcast_packets': 0 } match = re.findall(re_errors, interface, flags=re.M) if match: intf_counter['rx_errors'] = process_counts(match[0]) if len(match) == 2: intf_counter['tx_errors'] = process_counts(match[1]) match = re.findall(re_dicards, interface, flags=re.M) if len(match) == 2: intf_counter['rx_discards'] = process_counts(match[0]) intf_counter['tx_discards'] = process_counts(match[1]) match = re.findall(re_unicast, interface, flags=re.M) if len(match) == 2: intf_counter['rx_unicast_packets'] = process_counts(match[0]) intf_counter['tx_unicast_packets'] = process_counts(match[1]) match = re.findall(re_multicast, interface, flags=re.M) if len(match) == 2: intf_counter['rx_multicast_packets'] = process_counts(match[0]) intf_counter['tx_multicast_packets'] = process_counts(match[1]) match = re.findall(re_broadcast, interface, flags=re.M) if len(match) == 2: intf_counter['rx_broadcast_packets'] = process_counts(match[0]) intf_counter['tx_broadcast_packets'] = process_counts(match[1]) match = re.findall(re_rx_octets, interface, flags=re.M) if match: intf_counter['rx_octets'] = process_counts(match[0]) match = re.findall(re_tx_octets, interface, flags=re.M) if match: intf_counter['tx_octets'] = process_counts(match[0]) interfaces.update({intf_name: intf_counter}) return interfaces def get_environment(self): """ Return environment details. Sample output: { "cpu": { "0": { "%usage": 18.0 } }, "fans": { "FAN1": { "status": true } }, "memory": { "available_ram": 3884224, "used_ram": 784552 }, "power": { "PWR1": { "capacity": 600.0, "output": 92.0, "status": true } }, "temperature": { "CPU": { "is_alert": false, "is_critical": false, "temperature": 45.0 } } } """ environment = {} fan_cmd = 'display device fan' power_cmd = 'display device power' temp_cmd = 'display device temperature all' cpu_cmd = 'display cpu' mem_cmd = 'display memory' output = self.device.send_command(fan_cmd) environment.setdefault('fans', {}) match = re.findall(r"(?P<id>FAN\S+).+(?P<status>Normal|Abnormal)", output, re.M) # if match: for fan in match: status = True if fan[1] == "Normal" else False environment['fans'].setdefault(fan[0], {})['status'] = status output = self.device.send_command(power_cmd) environment.setdefault('power', {}) re_power = r"(?P<id>PWR\S+).+(?P<status>Supply|NotSupply|Sleep)\s+\S+\s+\S+\s+" \ r"(?P<output>\d+)\s+(?P<capacity>\d+)" match = re.findall(re_power, output, re.M) for power in match: status = True if power[1] == "Supply" else False environment['power'].setdefault(power[0], {})['status'] = status environment['power'][power[0]]['output'] = float(power[2]) environment['power'][power[0]]['capacity'] = float(power[3]) output = self.device.send_command(temp_cmd) environment.setdefault('temperature', {}) re_temp = r"(?P<name>\S+)\s+(?P<status>NORMAL|MAJOR|FATAL|ABNORMAL)\s+\S+\s+\S+\s+(?P<temperature>\d+)" match = re.findall(re_temp, output, re.M) for temp in match: environment['temperature'].setdefault(temp[0], {}) name = temp[0] is_alert = True if temp[1] == "MAJOR" else False is_critical = True if temp[1] == "FATAL" else False environment['temperature'][name]['temperature'] = float(temp[2]) environment['temperature'][name]['is_alert'] = is_alert environment['temperature'][name]['is_critical'] = is_critical output = self.device.send_command(cpu_cmd) environment.setdefault('cpu', {}) match = re.findall(r"cpu(?P<id>\d+)\s+(?P<usage>\d+)%", output, re.M) for cpu in match: usage = float(cpu[1]) environment['cpu'].setdefault(cpu[0], {})['%usage'] = usage output = self.device.send_command(mem_cmd) environment.setdefault('memory', {'available_ram': 0, 'used_ram': 0}) match = re.search(r"System Total Memory:\s+(?P<available_ram>\d+)", output, re.M) if match is not None: environment['memory']['available_ram'] = int( match.group("available_ram")) match = re.search(r"Total Memory Used:\s+(?P<used_ram>\d+)", output, re.M) if match is not None: environment['memory']['used_ram'] = int(match.group("used_ram")) return environment def get_arp_table(self, vrf=""): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) Sample output: [ { 'interface' : 'MgmtEth0/RSP0/CPU0/0', 'mac' : '5c:5e:ab:da:3c:f0', 'ip' : '172.17.17.1', 'age' : -1 }, { 'interface': 'MgmtEth0/RSP0/CPU0/0', 'mac' : '66:0e:94:96:e0:ff', 'ip' : '172.17.17.2', 'age' : -1 } ] """ if vrf: msg = "VRF support has not been implemented." raise NotImplementedError(msg) arp_table = [] output = self.device.send_command('display arp') re_arp = r"(?P<ip_address>\d+\.\d+\.\d+\.\d+)\s+(?P<mac>\S+)\s+(?P<exp>\d+|)\s+" \ r"(?P<type>I|D|S|O)\s+(?P<interface>\S+)" match = re.findall(re_arp, output, flags=re.M) for arp in match: if arp[2].isdigit(): exp = round(float(arp[2]) * 60, 1) else: exp = -1.0 entry = { 'interface': arp[4], 'mac': napalm.base.helpers.mac(arp[1]), 'ip': arp[0], 'age': exp } arp_table.append(entry) return arp_table def get_config(self, retrieve="all", full=False, sanitized=False): """ Get config from device. Returns the running configuration as dictionary. The candidate and startup are always empty string for now, since CE does not support candidate configuration. """ config = {'startup': '', 'running': '', 'candidate': ''} if retrieve.lower() in ('running', 'all'): command = 'display current-configuration' config['running'] = str(self.device.send_command(command)) if retrieve.lower() in ('startup', 'all'): # command = 'display saved-configuration last' # config['startup'] = str(self.device.send_command(command)) pass return config def get_lldp_neighbors(self): """ Return LLDP neighbors details. Sample output: { "10GE4/0/1": [ { "hostname": "HUAWEI", "port": "10GE4/0/25" }, { "hostname": "HUAWEI2", "port": "10GE4/0/26" } ] } """ results = {} command = 'display lldp neighbor brief' output = self.device.send_command(command) re_lldp = r"(?P<local>\S+)\s+\d+\s+(?P<port>\S+)\s+(?P<hostname>\S+)" match = re.findall(re_lldp, output, re.M) for neighbor in match: local_iface = neighbor[0] if local_iface not in results: results[local_iface] = [] neighbor_dict = dict() neighbor_dict['port'] = str(neighbor[1]) neighbor_dict['hostname'] = str(neighbor[2]) results[local_iface].append(neighbor_dict) return results def get_mac_address_table(self): """ Return the MAC address table. Sample output: [ { "active": true, "interface": "10GE1/0/1", "last_move": -1.0, "mac": "00:00:00:00:00:33", "moves": -1, "static": false, "vlan": 100 }, { "active": false, "interface": "10GE1/0/2", "last_move": -1.0, "mac": "00:00:00:00:00:01", "moves": -1, "static": true, "vlan": 200 } ] """ mac_address_table = [] command = 'display mac-address' output = self.device.send_command(command) re_mac = r"(?P<mac>\S+)\s+(?P<vlan>\d+|-)\S+\s+(?P<interface>\S+)\s+(?P<type>\w+)\s+(?P<age>\d+|-)" match = re.findall(re_mac, output, re.M) for mac_info in match: mac_dict = { 'mac': napalm.base.helpers.mac(mac_info[0]), 'interface': str(mac_info[2]), 'vlan': int(mac_info[1]), 'static': True if mac_info[3] == "static" else False, 'active': True if mac_info[3] == "dynamic" else False, 'moves': -1, 'last_move': -1.0 } mac_address_table.append(mac_dict) return mac_address_table def get_users(self): """ Return the configuration of the users. Sample output: { "admin": { "level": 3, "password": "", "sshkeys": [] } } """ result = {} command = 'display aaa local-user' output = self.device.send_command(command) re_user = r"(?P<username>\S+)\s+(Active|Block)(\s+\S+){3}\s+(\d+|--)" match = re.findall(re_user, output, re.M) try: for user in match: # level = -1 can not pass unit test level = 0 if user[3] == '--' else int(user[3]) result.setdefault(user[0], {})['level'] = level result[user[0]]['password'] = '' result[user[0]]['sshkeys'] = [] except Exception: msg = "Unexpected output data:\n{}".format(output) raise ValueError(msg) # Password is encrypted and cannot be read # command = 'display current-configuration | inc user' # output = self.device.send_command(command) return result def rollback(self): """Rollback to previous commit.""" if self.changed: self._load_config(self.backup_file) self.changed = False self._save_config() def ping(self, destination, source=c.PING_SOURCE, ttl=c.PING_TTL, timeout=c.PING_TIMEOUT, size=c.PING_SIZE, count=c.PING_COUNT, vrf=c.PING_VRF): """Execute ping on the device.""" ping_dict = {} command = 'ping' # Timeout in milliseconds to wait for each reply, the default is 2000 command += ' -t {}'.format(timeout * 1000) # Specify the number of data bytes to be sent command += ' -s {}'.format(size) # Specify the number of echo requests to be sent command += ' -c {}'.format(count) if source != '': command += ' -a {}'.format(source) command += ' {}'.format(destination) output = self.device.send_command(command) if 'Error' in output: ping_dict['error'] = output elif 'PING' in output: ping_dict['success'] = { 'probes_sent': 0, 'packet_loss': 0, 'rtt_min': 0.0, 'rtt_max': 0.0, 'rtt_avg': 0.0, 'rtt_stddev': 0.0, 'results': [] } match_sent = re.search(r"(\d+).+transmitted", output, re.M) match_received = re.search(r"(\d+).+received", output, re.M) try: probes_sent = int(match_sent.group(1)) probes_received = int(match_received.group(1)) ping_dict['success']['probes_sent'] = probes_sent ping_dict['success'][ 'packet_loss'] = probes_sent - probes_received except Exception: msg = "Unexpected output data:\n{}".format(output) raise ValueError(msg) match = re.search(r"min/avg/max = (\d+)/(\d+)/(\d+)", output, re.M) if match: ping_dict['success'].update({ 'rtt_min': float(match.group(1)), 'rtt_avg': float(match.group(2)), 'rtt_max': float(match.group(3)), }) results_array = [] match = re.findall(r"Reply from.+time=(\d+)", output, re.M) for i in match: results_array.append({ 'ip_address': str(destination), 'rtt': float(i) }) ping_dict['success'].update({'results': results_array}) return ping_dict def __get_snmp_information(self): snmp_information = {} # command = 'display snmp-agent sys-info' # output = self.device.send_command(command) snmp_information = { 'contact': str(''), 'location': str(''), 'community': {}, 'chassis_id': str('') } return snmp_information def __get_lldp_neighbors_detail(self, interface=''): """ Return a detailed view of the LLDP neighbors as a dictionary. Sample output: { 'TenGigE0/0/0/8': [ { 'parent_interface': u'Bundle-Ether8', 'remote_chassis_id': u'8c60.4f69.e96c', 'remote_system_name': u'switch', 'remote_port': u'Eth2/2/1', 'remote_port_description': u'Ethernet2/2/1', 'remote_system_description': u'''huawei os''', 'remote_system_capab': u'B, R', 'remote_system_enable_capab': u'B' } ] } """ lldp_neighbors = {} return lldp_neighbors def __get_ntp_peers(self): """ Return the NTP peers configuration as dictionary. Sample output: { '192.168.0.1': {}, '17.72.148.53': {}, '37.187.56.220': {}, '162.158.20.18': {} } """ ntp_server = {} # command = "display ntp session" # output = self.device.send_command(command) return ntp_server def __get_ntp_servers(self): """ Return the NTP servers configuration as dictionary. Sample output: { '192.168.0.1': {}, '17.72.148.53': {}, '37.187.56.220': {}, '162.158.20.18': {} } """ ntp_server = {} # command = "display ntp trace" # output = self.device.send_command(command) return ntp_server def __get_ntp_stats(self): ntp_stats = [] # command = "display ntp status" # output = self.device.send_command(command) return ntp_stats @staticmethod def _separate_section(separator, content): if content == "": return [] # Break output into per-interface sections interface_lines = re.split(separator, content, flags=re.M) if len(interface_lines) == 1: msg = "Unexpected output data:\n{}".format(interface_lines) raise ValueError(msg) # Get rid of the blank data at the beginning interface_lines.pop(0) # Must be pairs of data (the separator and section corresponding to it) if len(interface_lines) % 2 != 0: msg = "Unexpected output data:\n{}".format(interface_lines) raise ValueError(msg) # Combine the separator and section into one string intf_iter = iter(interface_lines) try: new_interfaces = [line + next(intf_iter, '') for line in intf_iter] except TypeError: raise ValueError() return new_interfaces def _delete_file(self, filename): command = 'delete /unreserved /quiet {0}'.format(filename) self.device.send_command(command) def _save_config(self, filename=''): """Save the current running config to the given file.""" command = 'save {}'.format(filename) save_log = self.device.send_command(command, max_loops=10, expect_string=r'Y/N') # Search pattern will not be detected when set a new hostname, so don't use auto_find_prompt=False save_log += self.device.send_command('y', expect_string=r'<.+>') search_result = re.search("successfully", save_log, re.M) if search_result is None: msg = "Failed to save config. Command output:{}".format(save_log) raise CommandErrorException(msg) def _load_config(self, config_file): command = 'rollback configuration to file {0}'.format(config_file) rollback_result = self.device.send_command(command, expect_string=r'Y/N') rollback_result += self.device.send_command( 'y', expect_string=r'[<\[].+[>\]]') search_result = re.search("clear the information", rollback_result, re.M) if search_result is not None: rollback_result += self.device.send_command('y', expect_string=r'<.+>') search_result = re.search("succeeded|finished", rollback_result, re.M) if search_result is None: msg = "Failed to load config. Command output:{}".format( rollback_result) raise CommandErrorException(msg) def _replace_candidate(self, filename, config): if not filename: filename = self._create_tmp_file(config) else: if not os.path.isfile(filename): raise ReplaceConfigException( "File {} not found".format(filename)) self.replace_file = filename if not self._enough_space(self.replace_file): msg = 'Could not transfer file. Not enough space on device.' raise ReplaceConfigException(msg) need_transfer = True if self._check_file_exists(self.replace_file): if self._check_md5(self.replace_file): need_transfer = False if need_transfer: dest = os.path.basename(self.replace_file) # full_remote_path = 'flash:/{}'.format(dest) with paramiko.SSHClient() as ssh: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=self.hostname, username=self.username, password=self.password, port=self.port, look_for_keys=False) try: with paramiko.SFTPClient.from_transport( ssh.get_transport()) as sftp_client: sftp_client.put(self.replace_file, dest) # with SCPClient(ssh.get_transport()) as scp_client: # scp_client.put(self.replace_file, dest) except Exception as e: msg = 'Could not transfer file. There was an error during transfer:' + str( e) raise ReplaceConfigException(msg) self.config_replace = True if config and os.path.isfile(self.replace_file): os.remove(self.replace_file) def _verify_remote_file_exists(self, dst, file_system='flash:'): command = 'dir {0}/{1}'.format(file_system, dst) output = self.device.send_command(command) if 'No file found' in output: raise ReplaceConfigException('Could not transfer file.') def _check_file_exists(self, cfg_file): command = 'dir {}'.format(cfg_file) output = self.device.send_command(command) if 'No file found' in output: return False return True def _check_md5(self, dst): dst_hash = self._get_remote_md5(dst) src_hash = self._get_local_md5(dst) if src_hash == dst_hash: return True return False @staticmethod def _get_local_md5(dst, blocksize=2**20): md5 = hashlib.md5() local_file = open(dst, 'rb') buf = local_file.read(blocksize) while buf: md5.update(buf) buf = local_file.read(blocksize) local_file.close() return md5.hexdigest() def _get_remote_md5(self, dst): command = 'display system file-md5 {0}'.format(dst) output = self.device.send_command(command) filename = os.path.basename(dst) match = re.search(filename + r'\s+(?P<md5>\w+)', output, re.M) if match is None: msg = "Unexpected format: {}".format(output) raise ValueError(msg) return match.group('md5') def _commit_merge(self): commands = [ command for command in self.merge_candidate.splitlines() if command ] output = '' try: output += self.device.send_command('system-view', expect_string=r'\[.+\]') for command in commands: output += self.device.send_command(command, expect_string=r'\[.+\]') if self.device.check_config_mode(): check_error = re.search("error", output, re.IGNORECASE) if check_error is not None: return_log = self.device.send_command( 'return', expect_string=r'[<\[].+[>\]]') if 'Uncommitted configurations' in return_log: # Discard uncommitted configuration return_log += self.device.send_command( 'n', expect_string=r'<.+>') output += return_log raise MergeConfigException('Error while applying config!') output += self.device.send_command('commit', expect_string=r'\[.+\]') output += self.device.send_command('return', expect_string=r'<.+>') else: raise MergeConfigException('Not in configuration mode.') except Exception as e: msg = str(e) + '\nconfiguration output: ' + output raise MergeConfigException(msg) def _get_merge_diff(self): diff = [] running_config = self.get_config(retrieve='running')['running'] running_lines = running_config.splitlines() for line in self.merge_candidate.splitlines(): if line not in running_lines and line: if line[0].strip() != '!': diff.append(line) return '\n'.join(diff) def _get_diff(self, filename=None): """Get a diff between running config and a proposed file.""" if filename is None: return self.device.send_command('display configuration changes') return self.device.send_command( 'display configuration changes running file ' + filename) def _enough_space(self, filename): flash_size = self._get_flash_size() file_size = os.path.getsize(filename) if file_size > flash_size: return False return True def _get_flash_size(self): command = 'dir {}'.format('flash:') output = self.device.send_command(command) match = re.search(r'\(\d.*KB free\)', output, re.M) if match is None: msg = "Failed to get free space of flash (not match). Log: {}".format( output) raise ValueError(msg) kbytes_free = 0 num_list = map(int, re.findall(r'\d+', match.group())) for index, val in enumerate(reversed(num_list)): kbytes_free += val * (1000**index) bytes_free = kbytes_free * 1024 return bytes_free @staticmethod def _parse_uptime(uptime_str): """Return the uptime in seconds as an integer.""" (years, weeks, days, hours, minutes, seconds) = (0, 0, 0, 0, 0, 0) years_regx = re.search(r"(?P<year>\d+)\syear", uptime_str) if years_regx is not None: years = int(years_regx.group(1)) weeks_regx = re.search(r"(?P<week>\d+)\sweek", uptime_str) if weeks_regx is not None: weeks = int(weeks_regx.group(1)) days_regx = re.search(r"(?P<day>\d+)\sday", uptime_str) if days_regx is not None: days = int(days_regx.group(1)) hours_regx = re.search(r"(?P<hour>\d+)\shour", uptime_str) if hours_regx is not None: hours = int(hours_regx.group(1)) minutes_regx = re.search(r"(?P<minute>\d+)\sminute", uptime_str) if minutes_regx is not None: minutes = int(minutes_regx.group(1)) seconds_regx = re.search(r"(?P<second>\d+)\ssecond", uptime_str) if seconds_regx is not None: seconds = int(seconds_regx.group(1)) uptime_sec = (years * YEAR_SECONDS) + (weeks * WEEK_SECONDS) + (days * DAY_SECONDS) + \ (hours * 3600) + (minutes * 60) + seconds return uptime_sec @staticmethod def _create_tmp_file(config): tmp_dir = tempfile.gettempdir() rand_fname = str(uuid.uuid4()) filename = os.path.join(tmp_dir, rand_fname) with open(filename, 'wt') as fobj: fobj.write(config) return filename
'password': '******', 'secret': 'cisco' } ios_l2_accesslayer3 = { 'device_type': 'cisco_ios', 'ip': '192.168.122.38', 'username':'******', 'password': '******', 'secret': 'cisco' } try: ssh_connection = ConnectHandler(**ios_l2_accesslayer1) print("connection success\n") ssh_connection.enable() print(ssh_connection.find_prompt()) ports = ["gig 0/0", "gig 0/1 ", "gig1/0"] for com in ports: commands = ['int' + " " + str(com), 'switchport trunk encapsulation dot1q', 'switchport mode trunk', 'exit'] out = ssh_connection.send_config_set(commands) time.sleep(5) ssh_connection.save_config(self, 'write mem', False, '') print(out) except:
print(" ") print("That is not the correct MAC Address format. Please try again....") exit() # creates Netmiko connection profile wlc = { 'device_type': 'cisco_wlc', 'host': WLCName, 'username': username, 'password': password, 'global_delay_factor': 4 } print(" ") print(" ") print("Connecting to " + WLCName + ".................................") net_connect = ConnectHandler(**wlc) print("Succesfully Connected to " + WLCName) print(" ") print("Checking for client " + clientMAC) output = net_connect.send_command("show client summary ") findclientmac = output.find(clientMAC) #Checks to see if the MAC address is present if output.find(clientMAC) != -1: print(" ") print("Device with MAC address " + clientMAC + " is connected to " + WLCName + ", getting client details.................") print(" ") clientdetail = net_connect.send_command("show client detail " + clientMAC) print(clientdetail) else: print("Device with MAC address " + clientMAC + " is NOT found on " +
def conn(device): return ConnectHandler(**device)
interface = output.split('\n') interface.pop() for x in interface: device = x.split(',') hostname = device[0] SW = { 'device_type': 'cisco_ios', 'ip': hostname, 'username': '******', 'password': '******', 'verbose': False, } print("Creating portchannel in " + hostname) net_connect = ConnectHandler(**SW) portChannel = device[1] interf = device[2:] for y in interf: print("interface " + y + "\n" + "switchport \n" + "channel-group " + portChannel + " mode active\n") net_connect.send_config_set("interface " + y + "\n" + "switchport \n" + "channel-group " + portChannel + " mode active\n") print("interface port-channel " + portChannel + "\n" + "description [UPLINK] R1(Fast1/1)\n" + "switchport \n" + "switchport trunk encapsulation dot1q\n" + "switchport mode trunk\n" + "logging event link-status\n") net_connect.send_config_set("interface " + portChannel + "\n" + "description [UPLINK] R1(Fast1/1)" +
from getpass import getpass from datetime import datetime password = getpass() lldp_nei = 'show lldp neighbors' nxos_2 = { "host": "nxos2.lasthop.io", "username": "******", "password": password, "device_type": "cisco_ios", "global_delay_factor": 2, } net_connect = ConnectHandler(**nxos_2) print(net_connect.find_prompt()) start_time = datetime.now() lldp_output = net_connect.send_command(lldp_nei, strip_command=False, strip_prompt=False) end_time = datetime.now() print("*" * 80) print(lldp_output) print("*" * 80) print("\n\n Execution Time: {}".format(end_time - start_time)) start_time = datetime.now()
class SSHjob: """SSHjob defines a class for a job running through SSH by calling the module netmiko. ... Attributes ---------- net_connect : netmiko return object. backup_ret : str The return of running backup on vmanage. ret1 : str The first return, copy backup file. ret2 : str The second return, copy zero size file. Methods ------- connect(): Call the netmiko to connect. run_backup(): Run backup request on vmanage. copy_backup_file(): Copy backup file through scp. copy_zero_file(): Copy zero size file to vmanage. disconnect(): Disconnect vmanage """ def __init__(self): self.net_connect = None self.backup_ret = None self.ret1 = None self.ret2 = None def connect(self): self.net_connect = ConnectHandler(**login_info) def run_backup(self): backup_cmd = ("request nms configuration-db backup path \ /home/admin/confdb_backup" + date) self.backup_ret = self.net_connect.send_command(backup_cmd) def copy_backup_file(self): runcmd = ("scp -i " + keyfile + " " + login_info["username"] + "@" + login_info["host"] + ":" + "/home/admin/confdb_backup" + date + ".tar.gz " + backup_path) self.ret1 = str( subprocess.run( runcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", timeout=5, )) def copy_zero_file(self): runcmd = ("touch " + zerofile + " && " + "scp -i vmanage " + zerofile + " admin@" + login_info["host"] + ":/home/admin/" + " && " + "rm " + zerofile) self.ret2 = str( subprocess.run( runcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", timeout=5, )) def disconnect(self): self.net_connect.disconnect()
from netmiko import ConnectHandler import getpass import json import csv # Set username and password username = input('Enter your SSH username here: ') password = getpass.getpass() # Set login and device parameters ios_device_s1 = { 'device_type': 'cisco_ios', 'ip': '192.168.122.15', 'username': username, 'password': password } # Make a list of all device all_devices = [ios_device_s1] # Iterate through all your devices for device in all_devices: print(f"Connecting to device: " + device['ip']) net_connect = ConnectHandler(**device) output = net_connect.send_command('show interface status') print(output) filename = f"port_security-{device['ip']}.json" print('-------------- Writing Port Security table------------') with open(filename, 'w') as f: port = json.dump(output, f)
def BasicConfHostnameExecute(self): #Try statement to ensure that any errors connecting and configuring the device are handled gracefully and the user is informed of what the potential error was using popups try: hostname = self.ids._Basic_Conf_Hostname_Layout_.ids.HostnameTextInput.text #Try statement to ensure the IP address entered is valid. If it is an invalid address the ipaddress module will raise a value error, at which point the user is informed that a valid IP address is required using a popup try: device_ip_address = self.ids._IPv4_Target_Device_Layout_.ids.IPv4AddressTextInput.text ipaddress.ip_address(device_ip_address) #ipaddress raises a value error when an invalid IP address is used except ValueError: Factory.InvalidIPAddressPopup().open() return #Exit from the function #If statement to ensure user has entered a username or password, if not a warning popup is raised if App.get_running_app( ).device_username == '' or App.get_running_app( ).device_password == '': Factory.NoUserOrPassPopup().open() return #Exit from the function else: device_username = App.get_running_app().device_username device_password = App.get_running_app().device_password device = { 'device_type': 'cisco_ios', 'ip': device_ip_address, 'username': device_username, 'password': device_password, } config_commands = ["hostname " + hostname] net_connect = ConnectHandler(**device) net_connect.send_config_set(config_commands) #Set the password and username back to empty after completion of configuration App.get_running_app().device_username = '' App.get_running_app().device_password = '' #Create and display a popup to inform the user of the successful configuration popup = Popup( title='', content=Label( markup=True, text="Successfully set '[b]" + hostname + "[/b]' as hostname of device with IP address '[b]" + device_ip_address + "[/b]'"), size_hint=(0.7, 0.3)) popup.open() #Except error to catch when Credentials are incorrect, informs the user of the error using a popup defined in the MainApplication.kv except AuthenticationException: Factory.NetmikoAuthenticateFailurePopup().open() #Except error to catch when Netmiko timeouts and is unable to connect to device, informs the user of the error using a popup defined in the MainApplication.kv except NetMikoTimeoutException: Factory.NetmikoTimeoutPopup().open()
def connect(self): self.net_connect = ConnectHandler(**login_info)
#!/usr/bin/env python from getpass import getpass from netmiko import ConnectHandler, file_transfer password = getpass() cisco = { 'device_type': 'cisco_ios', 'host': 'cisco1.twb-tech.com', 'username': '******', 'password': password, } source_file = 'test1.txt' dest_file = 'test1.txt' direction = 'put' file_system = 'flash:' ssh_conn = ConnectHandler(**cisco) transfer_dict = file_transfer(ssh_conn, source_file=source_file, dest_file=dest_file, file_system=file_system, direction=direction, overwrite_file=True) print(transfer_dict)
import os from getpass import getpass from netmiko import ConnectHandler devices = ['nxos1.lasthop.io', 'nxos2.lasthop.io'] for device in devices: device1 = { "host": device, "username": "******", "password": "******", "device_type": "cisco_nxos", "session_log": "my_session.txt", } net_connect = ConnectHandler(**device1) output = net_connect.send_config_from_file('my_changes.txt') print(output) save = net_connect.save_config() print(save) net_connect.disconnect()
def backend(src,dst): src=src dst=dst arr=[] count=0 setofnames=set() dictofnames={} dictofobj={} name='' s={src} now=src honame=set() exit=dict() entry=dict() entryrev=dict() ls=[] ls.append(now) extract=set() p='' boo=True intojson=[] while(len(s)>0): now=ls[0] rem=paramiko.SSHClient() rem.set_missing_host_key_policy(paramiko.AutoAddPolicy()) boo=True while boo: try: rem.connect(now,port=22, username='******',password='******') boo=False print ("SSH connection established for getting the version - ",now) stdin,stdout,stderr=rem.exec_command("show version") except Exception as e: print("Error in ssh connection, Trying again. Error - ",e) boo=True output=stdout.readlines() print(output) output='\n'.join(output) k9=output.replace('\n',' ') print("\n\n\n\n") print(k9) k9=k9.split() print("\n\n\n\n") print(k9) a=k9.index('Cisco') #print(a) #print(k9[a+1]) ios_ver='' verdict={} if (k9[a+1]=='IOS'): if (k9[a+2]=='XE'): ios_ver='IOS_XE' else: ios_ver='IOS' else: ios_ver='NEXUS' print(ios_ver) verdict['soft_ver']=ios_ver if ios_ver=='NEXUS': var=k9.index('BIOS:') var3=k9.index('kickstart:') verdict['version']="BIOS: "+k9[var+2]+" Kickstart: "+k9[var3+2] var=k9.index('uptime') var2=k9.index('second(s)') verdict['uptime']=' '.join(k9[var+2:var2+1]) var=k9.index('Hardware') verdict['hardware']=' '.join(k9[var+1:var+3]) var=k9.index('Reason:') verdict['reload_reason']=k9[var+1] elif ios_ver=='IOS_XE': var=k9.index('weeks,') var2=k9.index('minutes') verdict['uptime']=' '.join(k9[var-1:var2+1]) var=k9.index('Last') var2=k9.index('This') verdict['reload_reason']=' '.join(k9[var+3:var2]) var=k9.index('Version') verdict['version']=k9[var+1] var=k9.index('Release') verdict['hardware']=k9[var+4] else: var=k9.index('Version') verdict['version']=' '.join(k9[var+1][:-1]) var=k9.index('Software,') verdict['hardware']=k9[var+1] var=k9.index('uptime') var2=k9.index('minutes') verdict['uptime']=' '.join(k9[var+2:var2+1]) var=k9.index('reason:') var2=k9.index('This') verdict['reload_reason']=' '.join(k9[var+1:var2]) print(verdict) rem.close() boo=True while boo: try: ssh= ConnectHandler(device_type=ios_ver,host=now,username="******",password="******") boo=False except Exception as e: boo=True print(" Connection error, trying again ",e) #ret=ssh.send_command("en") boo=True while boo: try: name=ssh.find_prompt() boo=False except Exception as e: print(str(e)) print("Trying again") boo=True if not(re.match("^[A-Z]{3}-{2}[A-Z]{2}[0-9]{2}#{1}$",name)): boo=True print(" Name Received Incorrect- Trying again "+name) name=name[:-1] if name not in setofnames: setofnames.add(name) dictofnames[name]=count k=router(name) arr.append(k) dictofobj[name]=k dictofobj[name].addconnect(ssh) dictofobj[name].addsship(now) count+=1 dictofobj[name].gennodedict['version']=verdict print(name) honame.add(name) print("dict of names ") print(dictofnames) boo2=True while boo2: boo=True while boo: try: ret=ssh.send_command("sh ip route "+dst+" | include Known via") boo=False except Exception as e: boo=True print("1 Exception Handled- Trying again") print(" return from sh ip route | inc known via ") print(ret) if not ret: print("1 Trying again") boo=True elif isinstance(ret,list): print("1 Return from sh ip route is a list, trying again") boo=True elif len(ret.split())>=3: boo=False else: print("1 Trying Again sh ip route") boo=True print(" Name "+name+" show ip route | i known via") print(ret) ret=ret.split() prot=ret[2][1:] print("PROT- "+prot) if prot!='bgp' and prot !='connected",' and prot!='eigrp': boo2=True print(" Protocol received isn't correct. Trying Again ") else: boo2=False if prot=='bgp': dst1=dst fl=0 print("Prot BGP") while fl!=2: boo=True while boo: try: ret=ssh.send_command("sh ip route "+dst1) boo=False except: boo=True print("2 Exception Handled- Trying again") if not ret: boo=True print("2 Trying again") elif isinstance(ret,list): print("2 Return from sh ip route is a list, trying again") boo=True elif len(ret.split())>3: boo=False else: boo=True print("2 Trying again") print("\tBGP- sh ip route for dst "+dst1) print(ret) ret=ret.split("\n") fl=0 for i in ret: i=i.split() print("splitting ret") print(i) if i[0]=='*': nxt=i[1] if nxt=='directly': x=i.index('via') hop=i[x+1] fl=2 break elif re.match('^(?:[0-9]{1,3}\.){3}([0-9]{1,3})',nxt): dst1=nxt if nxt[-1]==',': dst1=nxt[:-1] fl=1 break print("Name "+name+" BGP: next hop "+dst1+" exit interface "+hop) extract.add(dst1) s.add(dst1) ls.append(dst1) p='' p=hop+' '+dst1 if name not in exit.keys(): exit[name]=set() exit[name].add(p) boo=True while boo: try: ret=ssh.send_command("sh ip int brief | include "+hop) boo=False except: print("3 Exception Handled- Trying again") boo=True if not ret: boo=True elif isinstance(ret,list): print("3 Return from sh ip int brief is a list, trying again") boo=True elif len(ret.split())<6: boo=True else: boo=False ip=ret.split()[1] ctobj=dictofnames[name] arr[ctobj].addexit(p) dictofobj[name].adddictip(hop,ip) p='' elif prot=='connected",': boo=True while boo: try: ret=ssh.send_command("sh ip route "+dst+" | include directly") boo=False except: boo=True print("4 Exception Handled- Trying again") print(" Return from sh ip route dst i directly") print(ret) if not ret: boo=True print("4 Return from show ip route dst is null, Trying again") elif isinstance(ret,list): print("4 Return from sh ip route directly is a list, trying again") boo=True elif len(ret.split())>3: boo=False else: print("4 Trying again") boo=True print("Connected route- show ip route| i directly ") print(ret) ret=ret.split() p='' x=ret.index('via') p=ret[x+1] hop=ret[x+1] p=p+' directly' if name not in exit.keys(): exit[name]=set() exit[name].add(p) print(" Name "+name+" is connected to dst via "+p) ctobj=dictofnames[name] arr[ctobj].addexit(p) boo=True while boo: try: ret=ssh.send_command("sh ip int brief | include "+hop) boo=False except: print("5 Exception Handled- Trying again") boo=True if not ret: boo=True elif isinstance(ret,list): print("5 Return from sh ip int brief is a list, trying again") boo=True elif len(ret.split())<6: boo=True else: boo=False ip=ret.split()[1] dictofobj[name].adddictip(hop,ip) p='' else: boo=True while boo: try: ret=ssh.send_command("sh ip route "+dst+" | include via") boo=False except: boo=True print("6 Exception Handled- Trying again") print(" Return from sh ip route") print(ret) if not ret: boo=True print("6 Trying again") elif isinstance(ret,list): print("6 Return from sh ip route is a list, trying again") boo=True elif len(ret.split())>3: boo=False else: print("6 Trying again") boo=True print("output from sh ip route | inc via ") print(ret) print("Splitting") ret=ret.split('\n') for i in ret: i=i.split() print(i) t=0 for j in i: #print(j) if re.match('^(?:[0-9]{1,3}\.){3}([0-9]{1,3})',j): print("extract- "+j[:-1]) j=j[:-1] if j not in extract: extract.add(j) s.add(j) ls.append(j) t=1 if t==1: num=i.index('via') p=i[num+1] hop=i[num+1] p=p+' '+j if name not in exit.keys(): exit[name]=set() exit[name].add(p) ctobj=dictofnames[name] #print("ctobj "+ctobj) arr[ctobj].addexit(p) print("hop ",hop) boo=True ret1="" while boo: try: ret1=ssh.send_command("sh ip int brief | include "+hop) boo=False except: print("6-2 Exception Handled- Trying again") boo=True print(" Return ") print(ret1) print(len(ret1.split())) #print(ret1.split()[0]) if not ret1: boo=True elif isinstance(ret1,list): print("6-2 Return from sh ip int brief is a list, trying again") boo=True elif len(ret1.split())<5: boo=True else: boo=False ip=ret1.split()[1] dictofobj[name].adddictip(hop,ip) p='' break extract.clear() s.remove(now) ls.remove(now) if now!=src: boo=True while boo: try: ret=ssh.send_command("sh ip int brief | include "+now) boo=False except: print("7 Exception Handled- Trying again") boo=True print(" return from sh ip int brief | inc dest at dest ") print(ret) print(len(ret.split())) if not ret: print("7 null") boo=True elif isinstance(ret,list): print("7 Return from sh ip route is a list, trying again") boo=True elif len(ret.split())<6: boo=True print("7 Trying Again") else: boo=False print(" Name "+name+" sh ip int brief | include "+now) print(ret) ret=ret.split() if name not in entry.keys(): entry[name]=set() p='' p=ret[0] hop=ret[0] ip=now p=p+' '+now entry[name].add(p) ctobj=dictofnames[name] arr[ctobj].addentry(p) dictofobj[name].adddictip(hop,ip) entryrev[now]=set() p='' p=name+' '+ret[0] entryrev[now].add(p) boo=True while boo: try: #device = {"device_type": "autodetect","host":dst,"username": "******","password":"******"} #guesser = SSHDetect(**device) #best_match = guesser.autodetect() #print(best_match,guesser.potential_matches) ssh=ConnectHandler(device_type="cisco_ios",host=dst,username="******",password="******") boo=False except Exception as e: boo=True print(" Connection error, trying again ",e,dst) boo=True while boo: try: name=ssh.find_prompt() boo=False except Exception as e: print(str(e)) print("Find Prompt errTrying Again") boo=True name=name[:-1] honame.add(name) if name not in setofnames: setofnames.add(name) dictofnames[name]=count k1=router(name) arr.append(k1) dictofobj[name]=k1 dictofobj[name].addconnect(ssh) count+=1 boo=True while boo: try: ret=ssh.send_command("sh ip int brief | include "+dst) boo=False except: print("8 Exception Handled- Trying again") boo=True print(" return from sh ip int brief | inc dest ") print(ret) if not ret: boo=True elif isinstance(ret,list): print("8 Return from sh ip int brief is a list, trying again") boo=True elif len(ret.split())<6: boo=True print("8 Trying Again") else: boo=False ret=ret.split() #print(ret) if name not in entry.keys(): entry[name]=set() p='' p=ret[0] p=p+' '+'directly' entry[name].add(p) hop=ret[0] ip=dst ctobj=dictofnames[name] arr[ctobj].addentry(p) dictofobj[name].adddictip(hop,ip) p='' entryrev['directly']=set() p=name+' '+ret[0] entryrev['directly'].add(p) print("Entry interfaces ") print(entry) print() print(" Exit interfaces ") print(exit) print() print(" Entry Reverse ") print(entryrev) ff=0 for nme in setofnames: ssh=dictofobj[nme].handle #general_node_parameters boo=True while boo: try: ret=ssh.send_command("sh proc cpu | ex 0.0",use_textfsm=True) boo=False except: print("9 Exception Raised , Trying again") boo=True if not(isinstance(ret,list)): boo=True print("9 return from sh proc cpu not proper, trying again") else: boo=False #parse the return from show environment and take out parameters like ct1=0 for line in ret: if ct1==0: cpu={} cpu['cpu_5_sec']=line['cpu_5_sec'] cpu['cpu_1_min']=line['cpu_1_min'] cpu['cpu_5_min']=line['cpu_5_min'] dictofobj[nme].gennodedict['CPU']=cpu combine={} combine['process']=line['process'] combine['proc_5_sec']=line['proc_5_sec'] combine['proc_1_min']=line['proc_1_min'] combine['proc_5_min']=line['proc_5_min'] dictofobj[nme].gennodedict[line['pid']]=combine ct1+=1 #parsing sh ip route boo=True while boo: try: ret=ssh.send_command("sh ip route") boo=False except: print("10 Exception Raised , Trying again") boo=True print(ret) if not ret: boo=True elif isinstance(ret,list): print("10 Return from sh ip route is a list, trying again") boo=True else: boo=False ret=ret.split('\n') gen={} ct1=0 print("RETURN: " ,ret) for line in ret: print("LINE: ",line) line2=line.split() print("Splitted LINE: ",line2) if not(not(line2)) and line2[0]!='S' and line2[0]!='C' and line2[0]!='S*' and 'via' in line2 and line2[0]=='D' and line2[0]=='B': pos=line2.index('via') if line2[pos+2][0:2]=='00': ct1+=1 gen[ct1]=line print(line) dictofobj[nme].gennodedict['ip_route_00']=gen #keys for gen dict is just numbers with no significance. display only values #dictofobj[nme].gennodedict['redundant_power']= #-----------------------------------------Harshad------------------------------------------------------------------------------------------ boo=True while boo: ans=ans1=0 try: ans=ssh.send_command("show ip protocols | include bgp") ans1=ssh.send_command("show ip protocols | include eigrp") boo=False except: print("9-2 Exception raised in sh ip protocols, trying again ") boo=True print(" sh ip protocols | i bgp ") print(ans) print(" sh ip protocols | i eigrp") print(ans1) if not(isinstance(ans,str)) or not(isinstance(ans1,str)): boo=True print("9-2 Return from sh ip protocols not proper. Trying again") elif not ans and not ans1: print("9-2 Return null from both protocols, trying again ") boo=True elif (not(ans1) and len(ans.split())<5) or (not(ans) and len(ans1.split())<5): print(" 9-2-1 Return from sh ip protocols not proper. Trying again") boo=True elif not(not(ans)) and len(ans.split())<5 and not(not(ans1)) and len(ans1.split())<5: print(" 9-2-3 Return from sh ip protocols not proper. Trying again") boo=True else: boo=False bgp=ans.split("\n") eigrp=ans1.split("\n") bgp_sub='"bgp' eigrp_sub='"eigrp' flag1=0 flag2=0 for text in bgp: if bgp_sub in text: flag1=1 break for text in eigrp: if eigrp_sub in text: flag2=1 break if flag2==1: print("eigrp there") #call bgp func boo=True while boo: try: ans=ssh.send_command("show ip eigrp neighbors") boo=False except: print("9-3 Exception handled. Error in sh ip eigrp neigh. Trying again ") boo=True print(" Return from sh ip eigrp neighbors ") print(ans) if not ans: print('Null returned from show ip eigrp neighbors') boo=True elif not(isinstance(ans,str)): print('not a string, returned from show ip eigrp neighbors') boo=True elif len(ans.split())<3: print('size less, returned from show ip eigrp neighbors') boo=True else: boo=False boo=True while boo: try: template=open('cisco_ios_show_ip_eigrp_neighbors.template') res_template=textfsm.TextFSM(template) ans_final=res_template.ParseText(ans) boo=False except Exception as e: print(e) print("9-4 Exception in Textfsm, Trying again") boo=True print(ans_final) hello={} j=0 dictofobj[nme].gennodedict['eigrp_neigh']=dict() for i in range(0,len(ans_final)): hello={} hello['neighbor']=ans_final[i][1] hello['uptime']=ans_final[i][4] hello['srtt']=ans_final[i][5] hello['rto']=ans_final[i][6] #dictofobj[nme].gennodedict['eigrp_neigh'] dictofobj[nme].gennodedict['eigrp_neigh'][ans_final[i][1]]=dict() dictofobj[nme].gennodedict['eigrp_neigh'][ans_final[i][1]]=hello if flag1==1: print("bgp there") ans=ssh.send_command("show ip bgp summary") print(ans) template=open('cisco_ios_show_ip_bgp_summary.template') res_template=textfsm.TextFSM(template) ans_final=res_template.ParseText(ans) print(ans_final) hello={} j=0 dictofobj[nme].gennodedict['bgp_neigh']=dict() for i in range(0,len(ans_final)): hello={} hello['neighbor']=ans_final[i][2] hello['AS']=ans_final[i][3] hello['up/down']=ans_final[i][5] dictofobj[nme].gennodedict['bgp_neigh'][ans_final[i][2]]=dict() dictofobj[nme].gennodedict['bgp_neigh'][ans_final[i][2]]=hello #---------------------------------------------------------------------------------------------------------------------------------------------- #------------------------------------------Neeraj----------------------------------------------------------------------------------------------- boo=True while boo: try: ret = ssh.send_command("show proc mem | include Total") boo=False except: print(" 9-4 Exception handled in sh proc mem | inc Pool Total. Trying Again") boo=True print("Return from show proc mem ") print(ret) if not ret: print(" 9-4 Returned value is null. Trying again ") boo=True elif not(isinstance(ret,str)): boo=True print("9-4 Returned value is not string, trying again ") elif ret.split()[0]!='Processor': print("9-4 Returned value on show proc mem is not proper, trying again") elif len(ret.split())<6: print("9-4 Returned value on show proc mem is not proper, trying again") boo=True else: boo=False def mb(str): return round(int(str)/1024/1024,2) #return 1 def percent(a,b): return round((int(a)/int(b)) * 100,2) memory = dict() ret = ret.split('\n') count=0 for line in ret: count=count+1 if(count>2): break; temp_vals = line.split(' ') vals = [] for string in temp_vals: if len(string.strip())>0: vals.append(string) print(vals) memory.update({vals[0]:{'total':mb(vals[3]),'used':mb(vals[5]),'free':mb(vals[7]),'percent':percent(vals[5],vals[3])}}) dictofobj[nme].gennodedict['Process_Memory']=dict() dictofobj[nme].gennodedict['Process_Memory']=memory print(memory) boo=True while boo: try: time1 = ssh.send_command("show clock") boo=False except: print("9-4 Exception handled. sh clock. Trying again") boo=True print("Time ") print(time1) if not time1: boo=True print("9-4 Return from show clock not proper. Trying again ") elif not(isinstance(time1,str)): print("9-4 Return from show clock in not string. Trying again") boo=True elif len(time1.split())<5: print("Time received not proper. Trying again ") boo=True else: boo=False time1=time1.split(" ")[3:5] time1 = time1[0]+" "+time1[1] print(time1) #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))) boo=True while boo: try: ret = ssh.send_command("show log | i down|Down|err|fail|Fail|drop|crash|MALLOCFAIL|") boo=False except: print("9-5 exception handled in show log. Trying again ") boo=True if not(isinstance(ret,str)): print("9-5 Return from show log in not string. Trying again") boo=True else: boo=False array = ret.split('\n') count=0 syslog = dict() for line in array: 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 dictofobj[nme].gennodedict['log']=syslog #--------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------ARAVIND----------------------------------------------------------------------------- map_return = {} print("For Spanning Tree KPI") print(dictofobj[nme].gennodedict['version']['hardware']) output_span='' if dictofobj[nme].gennodedict['version']['hardware']=='3725': boo=True while boo: try: output_span= ssh.send_command("sh spanning-tree active") boo=False except: boo=True print("9-6 Exception Raised in show spanning tree") if not output_span: print(" 9-6 Return from show spanning tree is null. Trying again ") boo=True elif not(isinstance(output_span,str)): boo=True print(" 9-6 Return from show spanning tree is not a string. Trying again ") elif len(output_span.split())<4: boo=True print(" 9-6 Return from show spanning tree is not proper. Trying again") else: boo=False l=output_span.split('\n') print("Spanning LIST") print(l) flag = 0 p = 12 m1={} for k in range(len(l)-6): if (k == p): print(" k ") print(k) print(" p ") print(p) print(l[k]) print(l[k + 6]) m1[l[k]] = l[k + 6] p += 9 p = 12 time.sleep(20) for lo in range(0, 2): for k in range(len(l)-6): if (k == p): print(" k ") print(k) print(" p ") print(p) # print(l[k]) # print(l[k+6]) if (m1[l[k]] != l[k + 6]): map_return[l[k]] = l[k + 6] print(l[k] + "\n" + l[k + 6]) flag = 1 else: print("No change Observed") flag = 0 p += 9 p = 12 time.sleep(20) if (flag == 0): print("No Changes in the Past 1 minute") flag = 0 print('\n\n\n') dictofobj[nme].gennodedict['spanning_tree']=map_return print("For show interface counters") print(dictofobj[nme].gennodedict['version']['hardware']) Int_count={} if dictofobj[nme].gennodedict['version']['hardware']=='3725': boo=True while boo: try: command = ssh.send_command("sh int counters error | ex 0") boo=False except: boo=True print("9-7 Exception handled - sh int counters error, Trying again") print("Return from show int counters error") print(command) if not command: print("9-7 Return from sh int counters errors is null, trying again") boo=True elif not(isinstance(command,str)): print("9-7 Return from sh int counters errors is not a string, trying again") boo=True elif len(command.split())<5: boo=True print("9-7 Return from sh int counters errors is not proper, trying again") else: boo=False output = command.split('\n') output.pop(0) if (output[1]): for i in output: print(i + '\n') Int_count = {i: 5 for i in output} else: print("Sorry Empty") dictofobj[nme].gennodedict['interface_counters_errors']=Int_count #--------------------------------------------------------------------------------------------------------------------------------------------------- #interface_level_details for interf in dictofobj[nme].dictint.keys(): print(interf+" in loop ") boo=True while boo: try: ret=ssh.send_command("sh interfaces "+interf,use_textfsm=True) boo=False except: print("11 Exception Raised , Trying again") boo=True continue print(ret) if not ret: boo=True elif isinstance(ret,str): print("11 output not in proper form, trying again ") boo=True else: boo=False #Parse the sh interface output and get the crc and other things out print(ret) line={} for line in ret: x=line.keys() if 'crc' in x: dictofobj[nme].dictint[interf]['crc']=line['crc'] if 'duplex' in x: dictofobj[nme].dictint[interf]['duplex']=line['duplex'] if 'reliability' in x: dictofobj[nme].dictint[interf]['reliability']=line['reliability'] if 'txload' in x: dictofobj[nme].dictint[interf]['txload']=line['txload'] if 'rxload' in x: dictofobj[nme].dictint[interf]['rxload']=line['rxload'] if 'speed' in x: dictofobj[nme].dictint[interf]['speed']=line['speed'] if 'collisions' in x: dictofobj[nme].dictint[interf]['collisions']=line['collisions'] if 'late_collision' in x: dictofobj[nme].dictint[interf]['late_collision']=line['late_collision'] if 'overrun' in x: dictofobj[nme].dictint[interf]['overrun']=line['overrun'] if 'interf_reset' in x: dictofobj[nme].dictint[interf]['interf_reset']=line['interf_reset'] if 'input_errors' in x: dictofobj[nme].dictint[interf]['input_errors']=line['input_errors'] if 'output_errors' in x: dictofobj[nme].dictint[interf]['output_errors']=line['output_errors'] if 'frame' in x: dictofobj[nme].dictint[interf]['frame']=line['frame'] if 'ignored' in x: dictofobj[nme].dictint[interf]['ignored']=line['ignored'] if 'bandwidth' in x: dictofobj[nme].dictint[interf]['bandwidth']=line['bandwidth'] if 'ignored' in x: dictofobj[nme].dictint[interf]['output_drops']=line['output_drops'] """boo=True while boo: try: ret=ssh.send_command("sh controllers "+interf) boo=False except: print("Exception Raised 2, Trying again") boo=True if not ret: boo=True elif len(boo.split('\n'))<4: boo=True else: boo=False #parse the ret and get the required parameters dictofobj[nme].dictint[interf]['']= dictofobj[nme].dictint[interf]['']= dictofobj[nme].dictint[interf]['']= dictofobj[nme].dictint[interf]['']= dictofobj[nme].dictint[interf]['']=""" forjson={} forjson['Name']=dict() #forjson['Name'][0]=dict() forjson['Name']['0']=nme forjson['Interface Dictionary']=dict() forjson['Interface Dictionary']=dictofobj[nme].dictint forjson['General Node']=dict() forjson['General Node']=dictofobj[nme].gennodedict intojson.append(forjson) ssh.disconnect() #for r in arr: # r.objprint() print( "FINAL OUTPUT ") print(exit) print(entryrev) print(intojson) return exit,entryrev,intojson
def BasicConfReloadExecute(self): #Try statement to ensure that any errors connecting and configuring the device are handled gracefully and the user is informed of what the potential error was using popups try: #Try statement to ensure the IP address entered is valid. If it is an invalid address the ipaddress module will raise a value error, at which point the user is informed that a valid IP address is required using a popup try: device_ip_address = self.ids._Basic_Conf_Reload_Layout_.ids.IPv4AddressTextInput.text ipaddress.ip_address(device_ip_address) #ipaddress raises a value error when an invalid IP address is used except ValueError: Factory.InvalidIPAddressPopup().open() return #Exit from the function #If statement to ensure user has entered a username or password if App.get_running_app( ).device_username == '' or App.get_running_app( ).device_password == '': Factory.NoUserOrPassPopup().open() return #Exit from the function else: device_username = App.get_running_app().device_username device_password = App.get_running_app().device_password device = { 'device_type': 'cisco_ios', 'ip': device_ip_address, 'username': device_username, 'password': device_password, } net_connect = ConnectHandler(**device) output = net_connect.send_command_timing('reload') #If statements that check the output for various strings to ensure that the correct commands are sent if 'Proceed with reload' in output: #If this string is detected the tool will send a newline, which will start the reload output += net_connect.send_command_timing('\n') #Set the password and username back to empty after completion of configuration App.get_running_app().device_username = '' App.get_running_app().device_password = '' #Creates and displays a popup to inform user that reload was successful popup = Popup( title='', content=Label( markup=True, text="Succesful reload of device with IP address '[b]" + device_ip_address + "[/b]'"), size_hint=(0.5, 0.3)) popup.open() if 'System configuration has been modified' in output: #If this string is detected the tool will send the below commands to start the reload output += net_connect.send_command_timing('yes') output += net_connect.send_command_timing('\n') #print(output) #Set the password and username back to empty after completion of configuration App.get_running_app().device_username = '' App.get_running_app().device_password = '' #Creates and displays a popup to inform user that reload was successful popup = Popup( title='', content=Label( markup=True, text="Succesful reload of device with IP address '[b]" + device_ip_address + "[/b]'"), size_hint=(0.5, 0.3)) popup.open() else: #If neither set of strings are detected the tool will display a failed configuration popup #Creates and displays a popup to inform user that reload has failed popup = Popup( title='', content=Label( markup=True, text="Failed to reload device with IP address '[b]" + device_ip_address + "[/b]'"), size_hint=(0.5, 0.3)) popup.open() #Except error to catch when Credentials are incorrect, informs the user of the error using a popup defined in the MainApplication.kv except AuthenticationException: Factory.NetmikoAuthenticateFailurePopup().open() #Except error to catch when Netmiko timeouts and is unable to connect to device, informs the user of the error using a popup defined in the MainApplication.kv except NetMikoTimeoutException: Factory.NetmikoTimeoutPopup().open()
# TOPOLOGY USED: https://www.dropbox.com/s/dkohdba5tpe6sxd/Cisco%20Network%20Automation%20-%20Beginner.png?dl=0 # Simple scrip to send show commands to the Router / Switch # root@NetworkAutomation-1:~# cat netmiko_test.py from netmiko import ConnectHandler iosv_l2 = { "device_type": "cisco_ios", "host": "192.168.122.82", # Switch: S2 IP address "username": "******", "password": "******", } net_connect = ConnectHandler(**iosv_l2) output = net_connect.send_command('sho ip int br') print(output) output = net_connect.send_command('sho vlan br') print(output) ''' OUTPUT: root@NetworkAutomation-1:~# root@NetworkAutomation-1:~# python3 netmiko_test.py Interface IP-Address OK? Method Status Protocol GigabitEthernet0/0 unassigned YES unset up up GigabitEthernet0/1 unassigned YES unset up up GigabitEthernet0/2 unassigned YES unset up up GigabitEthernet0/3 unassigned YES unset up up GigabitEthernet1/0 unassigned YES unset up up GigabitEthernet1/1 unassigned YES unset up up
class NetworkDevice(): def __init__(self, name, ip, user, pw): self.name = name self.ip_address = ip self.username = user self.password = pw logging.info( 'devclassNetmiko: created NetworkDevice object for IOS device: %s %s', name, ip) #---- Connect ----------------------------------------------- def connect(self): print('---------------------------------------------------------') print('--- devclassNetmiko ssh connecting to: ' + self.ip_address + ' ---') # Create netmiko session # device_type https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.netmiko_mod.html device_params = { 'device_type': 'cisco_ios', 'ip': self.ip_address, 'username': self.username, 'password': self.password, } # ssh connection to the device self.ssh_client = ConnectHandler(**device_params) # we put in log the device answer received_msg = '<=== {} Received from: {}' logging.info( received_msg.format(datetime.now().time(), self.ip_address)) #---- Get interfaces from device ---------------------------------- def get_interfaces(self): # we issue 'show interfaces summary' self.interfaces = self.ssh_client.send_command( 'show interfaces summary') # we put in log file prne.log the output of 'show interfaces summary' logging.info('show interfaces summary \n %s', self.interfaces) def multiple_commands(self): self.commands = [ 'do show ip int brie', 'do show ver', 'do show inventory' ] self.output = self.ssh_client.send_config_set(self.commands) logging.info('Multiple commands \n %s', self.output) #self.show = self.ssh_client.send_command('show interfaces summary') #---- Configure EIGRP AS ---------------------------------- def EIGRP_AS(self): self.commands = [ 'int l0', 'ip address 172.16.1.1 255.255.255.0', 'int l1', 'ip address 172.16.2.1 255.255.255.0', 'router eigrp 10', 'network 172.16.1.0', 'network 172.16.2.0', 'no network 172.16.255.0 0.0.0.3', 'eigrp router-id 2.2.2.2' ] self.output = self.ssh_client.send_config_set(self.commands) #self.show = self.ssh_client.send_command('show ip route') def EIGRP_AS_BR2(self): self.commands = [ 'int l0', 'ip address 172.16.4.1 255.255.255.0', 'int l1', 'ip address 172.16.5.1 255.255.255.0', 'int l2', 'ip address 172.16.6.1 255.255.255.0', 'router eigrp 10', 'network 172.16.4.0 0.0.3.255', 'eigrp router-id 3.3.3.3' ] self.output = self.ssh_client.send_config_set(self.commands) #self.show = self.ssh_client.send_command('show ip route') def templateInt(self): # yaml.safe_load trasform the yml file in python format [List of dictionaries] yamldir = os.path.dirname(__file__) yaml_template = os.path.join(yamldir, 'TemplateInterfaces1.yml') with open(yaml_template) as f: routers = yaml.safe_load(f) for router in routers: jinjadir = os.path.dirname(__file__) jinja_template = os.path.join(jinjadir, 'TemplateInterfaces1.j2') with open(jinja_template) as f: tfile = f.read( ) # tfile is TemplateInterfaces1.txt all in a single # row and each command split by \n template1 = jinja2.Template(tfile) # Convert each line into a list element for passing to Netmiko cfg_list = template1.render(router).split( '\n') # to merge {} with template1 self.output = self.ssh_client.send_config_set(cfg_list) logging.info('pushing conf \n %s', self.output)
from yaml import safe_load from netmiko import ConnectHandler #Read in host file into structed data with open("hosts.yml", "r") as file: host_root = safe_load(file) with open("commands.yml", "r") as file: commands = safe_load(file) for profile in host_root["Production"]: connection = ConnectHandler(**profile) print("Connected to device: " + profile["ip"]) for command in commands["commands"]: sent_command = connection.send_command(command) print(sent_command) print("-" * len(sent_command)) connection.disconnect()
class ASADevice(BaseDevice): """Cisco ASA Device Implementation.""" vendor = "cisco" def __init__(self, host, username, password, secret="", port=22, **kwargs): super().__init__(host, username, password, device_type="cisco_asa_ssh") self.native = None self.secret = secret self.port = int(port) self.global_delay_factor = kwargs.get("global_delay_factor", 1) self.delay_factor = kwargs.get("delay_factor", 1) self._connected = False self.open() def _enable(self): warnings.warn("_enable() is deprecated; use enable().", DeprecationWarning) self.enable() def _enter_config(self): self.enable() self.native.config_mode() def _file_copy_instance(self, src, dest=None, file_system="flash:"): if dest is None: dest = os.path.basename(src) fc = FileTransfer(self.native, src, dest, file_system=file_system) return fc def _get_file_system(self): """Determines the default file system or directory for device. Returns: str: The name of the default file system or directory for the device. Raises: FileSystemNotFound: When the module is unable to determine the default file system. """ raw_data = self.show("dir") try: file_system = re.match(r"\s*.*?(\S+:)", raw_data).group(1) except AttributeError: # TODO: Get proper hostname raise FileSystemNotFoundError(hostname=self.host, command="dir") return file_system def _image_booted(self, image_name, **vendor_specifics): version_data = self.show("show version") if re.search(image_name, version_data): return True return False def _interfaces_detailed_list(self): ip_int = self.show("show interface") ip_int_data = get_structured_data("cisco_asa_show_interface.template", ip_int) return ip_int_data def _raw_version_data(self): show_version_out = self.show("show version") try: version_data = get_structured_data("cisco_asa_show_version.template", show_version_out)[0] return version_data except IndexError: return {} def _send_command(self, command, expect=False, expect_string=""): if expect: if expect_string: response = self.native.send_command_expect(command, expect_string=expect_string) else: response = self.native.send_command_expect(command) else: response = self.native.send_command_timing(command) if "% " in response or "Error:" in response: raise CommandError(command, response) return response def _show_vlan(self): show_vlan_out = self.show("show vlan") show_vlan_data = get_structured_data("cisco_ios_show_vlan.template", show_vlan_out) return show_vlan_data def _uptime_components(self, uptime_full_string): match_days = re.search(r"(\d+) days?", uptime_full_string) match_hours = re.search(r"(\d+) hours?", uptime_full_string) match_minutes = re.search(r"(\d+) minutes?", uptime_full_string) days = int(match_days.group(1)) if match_days else 0 hours = int(match_hours.group(1)) if match_hours else 0 minutes = int(match_minutes.group(1)) if match_minutes else 0 return days, hours, minutes def _uptime_to_seconds(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) seconds = days * 24 * 60 * 60 seconds += hours * 60 * 60 seconds += minutes * 60 return seconds def _uptime_to_string(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) return "%02d:%02d:%02d:00" % (days, hours, minutes) def _wait_for_device_reboot(self, timeout=3600): start = time.time() while time.time() - start < timeout: try: self.open() return except: # noqa E722 pass # TODO: Get proper hostname parameter raise RebootTimeoutError(hostname=self.host, wait_time=timeout) def backup_running_config(self, filename): with open(filename, "w") as f: f.write(self.running_config) @property def boot_options(self): show_boot_out = self.show("show boot | i BOOT variable") # Improve regex to get only the first boot $var in the sequence! boot_path_regex = r"Current BOOT variable = (\S+):\/(\S+)" match = re.search(boot_path_regex, show_boot_out) if match: boot_image = match.group(2) else: boot_image = None return dict(sys=boot_image) def checkpoint(self, checkpoint_file): self.save(filename=checkpoint_file) def close(self): if self._connected: self.native.disconnect() self._connected = False def config(self, command): self._enter_config() self._send_command(command) self.native.exit_config_mode() def config_list(self, commands): self._enter_config() entered_commands = [] for command in commands: entered_commands.append(command) try: self._send_command(command) except CommandError as e: raise CommandListError(entered_commands, command, e.cli_error_msg) self.native.exit_config_mode() def enable(self): """Ensure device is in enable mode. Returns: None: Device prompt is set to enable mode. """ # Netmiko reports enable and config mode as being enabled if not self.native.check_enable_mode(): self.native.enable() # Ensure device is not in config mode if self.native.check_config_mode(): self.native.exit_config_mode() @property def facts(self): """Implement this once facts' re-factor is done. """ return {} def file_copy(self, src, dest=None, file_system=None): self.enable() if file_system is None: file_system = self._get_file_system() if not self.file_copy_remote_exists(src, dest, file_system): fc = self._file_copy_instance(src, dest, file_system=file_system) # if not self.fc.verify_space_available(): # raise FileTransferError('Not enough space available.') try: fc.enable_scp() fc.establish_scp_conn() fc.transfer_file() except: # noqa E722 raise FileTransferError finally: fc.close_scp_chan() if not self.file_copy_remote_exists(src, dest, file_system): raise FileTransferError( message="Attempted file copy, but could not validate file existed after transfer" ) # TODO: Make this an internal method since exposing file_copy should be sufficient def file_copy_remote_exists(self, src, dest=None, file_system=None): self.enable() if file_system is None: file_system = self._get_file_system() fc = self._file_copy_instance(src, dest, file_system=file_system) if fc.check_file_exists() and fc.compare_md5(): return True return False def install_os(self, image_name, **vendor_specifics): timeout = vendor_specifics.get("timeout", 3600) if not self._image_booted(image_name): self.set_boot_options(image_name, **vendor_specifics) self.reboot(confirm=True) self._wait_for_device_reboot(timeout=timeout) if not self._image_booted(image_name): raise OSInstallError(hostname=self.facts.get("hostname"), desired_boot=image_name) return True return False def open(self): if self._connected: try: self.native.find_prompt() except: # noqa E722 self._connected = False if not self._connected: self.native = ConnectHandler( device_type="cisco_asa", ip=self.host, username=self.username, password=self.password, port=self.port, global_delay_factor=self.global_delay_factor, secret=self.secret, verbose=False, ) self._connected = True def reboot(self, timer=0, confirm=False): if confirm: def handler(signum, frame): raise RebootSignal("Interrupting after reload") signal.signal(signal.SIGALRM, handler) signal.alarm(10) try: if timer > 0: first_response = self.show("reload in %d" % timer) else: first_response = self.show("reload") if "System configuration" in first_response: self.native.send_command_timing("no") self.native.send_command_timing("\n") except RebootSignal: signal.alarm(0) signal.alarm(0) else: print("Need to confirm reboot with confirm=True") def rollback(self, rollback_to): raise NotImplementedError @property def running_config(self): return self.show("show running-config", expect=True) def save(self, filename="startup-config"): command = "copy running-config %s" % filename # Changed to send_command_timing to not require a direct prompt return. self.native.send_command_timing(command) # If the user has enabled 'file prompt quiet' which dose not require any confirmation or feedback. # This will send return without requiring an OK. # Send a return to pass the [OK]? message - Increase delay_factor for looking for response. self.native.send_command_timing("\n", delay_factor=2) # Confirm that we have a valid prompt again before returning. self.native.find_prompt() return True def set_boot_options(self, image_name, **vendor_specifics): current_boot = self.show("show running-config | inc ^boot system ") file_system = vendor_specifics.get("file_system") if file_system is None: file_system = self._get_file_system() file_system_files = self.show("dir {0}".format(file_system)) if re.search(image_name, file_system_files) is None: raise NTCFileNotFoundError( # TODO: Update to use hostname hostname=self.host, file=image_name, dir=file_system, ) current_images = current_boot.splitlines() commands_to_exec = ["no {0}".format(image) for image in current_images] commands_to_exec.append("boot system {0}/{1}".format(file_system, image_name)) self.config_list(commands_to_exec) self.save() if self.boot_options["sys"] != image_name: raise CommandError( command="boot system {0}/{1}".format(file_system, image_name), message="Setting boot command did not yield expected results", ) def show(self, command, expect=False, expect_string=""): self.enable() return self._send_command(command, expect=expect, expect_string=expect_string) def show_list(self, commands): self.enable() responses = [] entered_commands = [] for command in commands: entered_commands.append(command) try: responses.append(self._send_command(command)) except CommandError as e: raise CommandListError(entered_commands, command, e.cli_error_msg) return responses @property def startup_config(self): return self.show("show startup-config")
with open('devices_file') as f: devices_list = f.read().splitlines() for devices in devices_list: print('Connecting to device" ' + devices) ip_address_of_device = devices ios_device = { 'device_type': 'cisco_ios', 'ip': ip_address_of_device, 'username': username, 'password': password } try: net_connect = ConnectHandler(**ios_device) 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: ' + str(unknown_error))
from netmiko import ConnectHandler device = ConnectHandler(device_type='cisco_ios', ip='192.168.101.11', username='******', password='******', secret='cisco123') SendingCommands = ["username Markus secret cisco123"] print(device.find_prompt()) device.enable() print(device.find_prompt()) device.config_mode() print(device.find_prompt()) output = device.send_config_set(SendingCommands) print(output) device.disconnect()
class Router: def __init__(self): self.net_connect = ConnectHandler(**homeRTR) def show_dhcp_binding(self, mac_end): command = 'show ip dhcp binding | incl ' + mac_end output = self.net_connect.send_command(command) # self.net_connect.disconnect() return output.split('\n') def ping_ipaddr(self, ipaddr): command = 'ping ' + ipaddr output = self.net_connect.send_command(command) # self.net_connect.disconnect() return output.split('\n') def show_arp(self, mac_end): command = 'show arp | incl ' + mac_end output = self.net_connect.send_command(command) # self.net_connect.disconnect() return output.split('\n') def add_dhcp_client(self, config_list): output = self.net_connect.send_config_set(config_list) return output.split('\n') def delete_dhcp_client(self, config_list): output = self.net_connect.send_config_set(config_list) return output.split('\n')