def main(): password = getpass() py_router_2 = { 'device_type':'cisco_ios', 'ip':'50.76.53.27', 'username':'******', 'password':password, 'port':8022, } rtr2 = ConnectHandler(**py_router_2) rtr2.config_mode() output = rtr2.check_config_mode() print "RTR Config mode is %s" % output if (output is True): #config_command = ['loggin buffered 5555'] #output = rtr2.send_config_set(config_command) output = rtr2.send_config_from_file(config_file='config_file.txt') print "Changes send to router.\n %s" % output rtr2.exit_config_mode() else: print "Could not get to config mode.\n"
def main(): rlist = [pynet1, pynet2] for router in rlist: rtr = ConnectHandler(**router) rtr.config_mode() rtr.send_config_from_file(config_file='configfile.txt') rtr.exit_config_mode()
def main(): '''Main function, opens connection, enters config mode, changes logging and verifies''' pynet_rtr2 = ConnectHandler(**RTR2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): pynet_rtr2.send_command("logging buffered 16384") pynet_rtr2.exit_config_mode() output = pynet_rtr2.send_command("show run | include logging buff") print output else: print "We are NOT in Config mode"
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'openstack-rb5', 'config_mode' : '(config)', } net_connect = ConnectHandler(**brocade_vdx) # Enter enable mode module.prompt_initial = net_connect.find_prompt() net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Send a set of config commands module.config_mode = net_connect.config_mode() config_commands = ['logging raslog console WARNING', 'interface vlan 20', 'banner motd test_message'] net_connect.send_config_set(config_commands) # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command('show vlan brief') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'n7k1#', 'base_prompt' : 'n7k1', 'interface_ip' : '10.3.3.245', 'config_mode' : '(config)' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' net_connect = ConnectHandler(**cisco_nxos) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) net_connect.enable() module.enable_prompt = net_connect.find_prompt() module.config_mode = net_connect.config_mode() config_commands = ['logging monitor 3', 'logging monitor 7', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command("show run | inc 'logging monitor'") net_connect.disconnect()
def main(): # Definition of rtr2. rtr2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': '******', 'port': 8022, } # Log into router. net_connect = ConnectHandler(**rtr2) # Check current logging buffer size. output = net_connect.send_command("show run | inc buffered") print print "Initial logging buffer size: " + output # Enter config mode, change logging buffer size, exit config mode. output = net_connect.config_mode() output = net_connect.send_command("logging buffer 64000") output = net_connect.exit_config_mode() # Check logging buffer size again. output = net_connect.send_command("show run | inc buffered") print "Final logging buffer size: " + output print
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'xe-test-rtr#', 'base_prompt' : 'xe-test-rtr', 'interface_ip' : '172.30.0.167', 'config_mode' : '(config)', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' net_connect = ConnectHandler(**cisco_xe) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) net_connect.enable() module.enable_prompt = net_connect.find_prompt() module.config_mode = net_connect.config_mode() config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command('show run | inc logging buffer') net_connect.disconnect()
def main(): device_list = getConfig() for device in device_list: print "Please input password for: " + device.get('rtr_name') device['password']=getpass() device.pop("rtr_name",None) conn=ConnectHandler(**device) conn.config_mode() if (conn.check_config_mode): print "In config" conn.exit_config_mode() print "Arp table\n" + conn.send_command("sh arp") if ('cisco_ios' in device.get('device_type')): config_commands = ["do show run | i buffered","logging buffered 12000","do sh run | i buffered"] output = conn.send_config_set(config_commands) print output output = conn.send_config_from_file(config_file='config_file.txt') print output
def main(): pynet2 = { 'device_type': 'cisco_ios', 'ip' : '50.76.53.27', 'username' : 'pyclass', 'port' : 8022, 'password' : '88newclass' } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): print "We're in config mode" else: print "Nope, We're NOT in config mode" print pynet_rtr2.find_prompt() pynet_rtr2.exit_config_mode() print pynet_rtr2.find_prompt()
def main(): password = getpass() py_router_2 = { 'device_type':'cisco_ios', 'ip':'50.76.53.27', 'username':'******', 'password':password, 'port':8022, } rtr2 = ConnectHandler(**py_router_2) rtr2.config_mode() output = rtr2.check_config_mode() print "RTR Config mode is %s" % output rtr2.exit_config_mode()
def main(): ''' Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2 ''' ip_address = raw_input("Enter IP address: ") password = getpass() pynet_rtr2['ip'] = ip_address pynet_rtr2['password'] = password ssh_conn = ConnectHandler(**pynet_rtr2) ssh_conn.config_mode() if ssh_conn.check_config_mode: ssh_conn.send_command('logging buffered 999999') ssh_conn.exit_config_mode() output = ssh_conn.send_command('show run | in logging') print output
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() out_2 = pynet_rtr2.send_command( "logging buffered 1234567" ) pynet_rtr2.exit_config_mode() out_2 = pynet_rtr2.send_command( "show logging" ) print print "-----------------------------------------------------------------------------" print "Logging setting on pynet rtr 2" print out_2 print "-----------------------------------------------------------------------------"
def main(): print 'Username:'******'device_type':DEV_TYPE, 'ip':dev, 'username':usern, 'password':passwd } # Initiating netmiko connection net_connect = ConnectHandler(**net_dev) resp = net_connect.find_prompt() print resp # Entering config mode net_connect.config_mode() # Verifying we're in config mode resp = net_connect.check_config_mode() print 'Entered Config mode? {}'.format(resp) # Exiting config mode net_connect.exit_config_mode()
def ssh_conn(**kwargs): """SSH to Device and send commands (Threaded)""" output_q = kwargs['output_q'] sout = [] try: net_connect = ConnectHandler(device_type=kwargs['Platform'], ip=kwargs['FQDN'], username=config['nsj']['username'], password=config['nsj']['password']) net_connect.enable() for s in kwargs['shcmds']: output = net_connect.send_command(s) #print(output) #output = net_connect.send_config_set(cfg_command) sout.append(output) if len(kwargs['confcmds']) > 0: net_connect.config_mode() for c in kwargs['confcmds']: output = "" logging.debug('Sending Command to %s: %s' % (kwargs['Name'], c)) if args.timing: output = net_connect.send_command_timing(c) else: output = net_connect.send_command(c) sout.append(output) net_connect.exit_config_mode() if args.wrmem: logging.info("Writing Mem on %s" % (kwargs['Name'])) net_connect.send_command("wr") sleep(20) net_connect.disconnect() except Exception as e: error = 'Error on {}: {}'.format(kwargs['FQDN'], e) logger.critical(error) #print('ERROR on ', kwargs['FQDN'], e) output = ERROR_PATTERN output_q.put({kwargs['Name']: sout})
def main(): # Definition of rtr2. rtr1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': '******', } rtr2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': '******', 'port': 8022, } # Create a list of all the routers. all_routers = [rtr1, rtr2] # Loop through all the routers and show arp. for a_router in all_routers: net_connect = ConnectHandler(**a_router) # Check current logging buffer size. print "\n>>>>>>>>> Device {0} <<<<<<<<<".format(a_router['device_type']) output = net_connect.send_command("show run | inc logging") print "Initial logging config: " print output print # Enter config mode, change logging buffer and console logging from file, # exit config mode. output = net_connect.config_mode() output = net_connect.send_config_from_file(config_file='config_file.txt') output = net_connect.exit_config_mode() # Check logging buffer size again. output = net_connect.send_command("show run | inc logging") print "Final logging config: " print output print ">>>>>>>>> End <<<<<<<<<\n"
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'vsr1000', 'router_prompt' : '<vsr1000>', 'interface_ip' : '192.168.112.11', 'config_mode' : '[vsr1000]', } show_ver_command = 'display version' multiple_line_command = 'display logbuffer' module.basic_command = 'display ip interface brief' net_connect = ConnectHandler(**hp_comware) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Enter config mode module.config_mode = net_connect.config_mode() # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Send a set of config commands config_commands = ['vlan 3000', 'name 3000-test'] net_connect.send_config_set(config_commands) # Verify config changes module.config_commands_output = net_connect.send_command('display vlan 3000') # Undo config changes net_connect.send_command('undo vlan 3000') net_connect.disconnect()
Pynet2Connect = ConnectHandler(**Pynet2) print "Logging in..." time.sleep(1) Pynet2Prompt = Pynet2Connect.find_prompt() print "\n", Pynet2Prompt, "\n\n" print "Entering configuration mode..." time.sleep(2) Pynet2Config = Pynet2Connect.config_mode() print "\n", Pynet2Config, "\n\n" print "Changing the buffer size..." time.sleep(2) Pynet2ConfigCommands = ['logging buffer 6666'] Pynet2ConfigChange = Pynet2Connect.send_config_set(Pynet2ConfigCommands) print "\n", Pynet2ConfigCommands, "\n\n" print "Exiting configuration mode..." time.sleep(2) Pynet2ExitConfig = Pynet2Connect.exit_config_mode() print "\n", Pynet2Prompt, "\n\n" print "Checking if the command took effect..." time.sleep(2) Pynet2ConfigChangeCheck = Pynet2Connect.send_command('show run | i logging') print "\n\n", Pynet2Prompt, "show run | i logging\n", Pynet2ConfigChangeCheck, "\n\n"
#!/usr/bin/env python from netmiko import ConnectHandler pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': '******', 'port': 8022 } pynet2_session = ConnectHandler(**pynet2) print pynet2_session.send_command('show run | inc logging') pynet2_session.config_mode() pynet2_session.send_config_from_file(config_file='commands_for_ex8.txt') pynet2_session.exit_config_mode() print pynet2_session.send_command('show run | inc logging')
'ip':'50.76.53.27', 'username':'******', 'password':password, 'port': 8022, } juniper_srx = { 'device_type':'juniper', 'ip':'50.76.53.27', 'username':'******', 'password': password, 'secret':'', 'port': 9822, } rtr1=ConnectHandler(**pynet1) rtr2=ConnectHandler(**pynet2) srx=ConnectHandler(**juniper_srx) print rtr1.find_prompt() rtr1.config_mode() rtr1.exit_config_mode() print rtr1.send_command('show ip int brief') print rtr1.send_command('show run | inc logging buffered') config_set=['logging buffered 65000'] print rtr1.send_config_set(config_set) print rtr1.send_command('show run | inc logging buffered') print dir(rtr1)
class Device(networktangents.NetworkDevice): """ Class container for all attributes and methods related to a Network Device """ def __init__(self, device_name, user_name, user_password, enable_password, device_type='cisco_ios'): super(Device, self).__init__(device_name, user_name, user_password, enable_password, device_type) self.DeviceName = device_name self.UserName = user_name self.UPassword = user_password self.EnablePassword = enable_password self.ShowVersion = '' self.ShowVersionBrief = '' self.ChassisModel = '' self.ShowRunning = '' self.SystemUpTime = '' self.Show_File_System = '' self.Interfaces = {} self.Vlans = {} self.base_ip_route = [] self.ShowModule = [] self.ShowCdpNeiDet = [] self.ShowMacAddress = [] self.ShowInterfacesStatus = [] self.ShowInterfaces = [] self.ShowInterfaceSwitchport = [] self.ShowInterfaceCapabilities = [] self.ShowEtherchannelPort = [] self.ShowVRF = [] self.ShowIPRoute = [] self.ShowIPRouteVrf = [] self.VRF = {} self.ShowVlan = '' self.ListIntLonNam = [] self.MacAddress = {} self.list_commands = [] """ testing using Netmiko as seems stable """ from netmiko import ConnectHandler self.Cisco_Device = { 'device_type': device_type, 'ip': self.DeviceName, 'username': self.UserName, 'password': self.UPassword, 'secret': self.EnablePassword, } self.Device_Connection = ConnectHandler(**self.Cisco_Device) def send_command(self, command): time.sleep(0.1) output = self.Device_Connection.send_command(command, delay_factor=.2) return output.splitlines() def disconnect(self): self.Device_Connection.disconnect() def show_version(self): self.ShowVersion = self.send_command("sh ver") self.SystemUpTime = netconparser.line_from_text("uptime is", self.ShowVersion) self.ShowVersionBrief = netconparser.show_ver_brief(self.ShowVersion) self.ChassisModel = netconparser.show_ver_model(self.ShowVersionBrief) def show_file_system(self): self.Show_File_System = self.send_command("show file systems") def show_module(self): self.ShowModule = self.send_command("sh module") def show_running(self): self.ShowRunning = self.send_command("sh run") def show_cdp_nei_det(self): self.ShowCdpNeiDet = self.send_command("show cdp nei det") def show_mac_address(self): self.ShowMacAddress = self.send_command("show mac address") def show_int(self): self.ShowInterfaces = self.send_command("show interfaces") def show_int_status(self): self.ShowInterfacesStatus = self.send_command("sh int status") def show_int_switchport(self): self.ShowInterfaceSwitchport = self.send_command("sh int switchport") def show_int_capabilities(self): self.ShowInterfaceCapabilities = self.send_command("sh int capabilities ") def show_vlan(self): self.ShowVlan = self.send_command("sh vlan") def show_vrf(self): self.VRF = netconparser.show_vrf_to_dictionary(self.send_command("sh ip vrf")) def populate_ip_route(self): self.base_ip_route = self.send_command("sh ip route") self.show_vrf() if len(self.VRF) > 0: for index in self.VRF.keys(): ip_route_per_vrf = self.send_command("sh ip route vrf " + index) self.VRF[index][2] = ip_route_per_vrf def show_etherchannelport(self): self.ShowEtherchannelPort = self.send_command("sh etherchannel port") def populate_vlans(self): """ :return: {vlan_id_int}: [Vlannumber_str, Vlanname, composite] """ self.show_vlan() self.Vlans = netconparser.show_vlan_to_dictionary(self.ShowVlan) def populate_mac_address(self): self.show_mac_address() # print("calling show mac add to dic") self.MacAddress = netconparser.show_mac_to_dictionary(self.ShowMacAddress) # print("\n\n\n", self.MacAddress, "\n\n\n") def populate_vrf(self): """ :return: {vrf_id_int}: [Vrfnumber_str, Vrfname, composite] """ self.show_vrf() self.VRF = netconparser.show_vrf_to_dictionary(self.ShowVRF) def populate_interfaces(self): """ runs 'sh int status', 'sh int', 'sh int switchport', 'sh int capabilities', 'sh mac add'; and fills in NetworkDevice.Interfaces, dictionary; items are Interface classes :return: """ self.show_int_status() self.show_int() listshowint = netconparser.show_interface_to_list(self.ShowInterfaces) self.show_int_switchport() listshowintswi = netconparser.show_interface_switchport_to_list(self.ShowInterfaceSwitchport) # print("calling populate mac add") self.populate_mac_address() for show_int_per_int in listshowint: # through "sh interface" per interface swi_int = ciscoint.Interface() swi_int.InterfaceName = show_int_per_int[0].split()[0] swi_int.InterfaceShortName = netconparser.int_name_to_int_short_name(swi_int.InterfaceName) swi_int.ShowInterfacePerInt = show_int_per_int self.Interfaces[swi_int.InterfaceShortName] = swi_int self.ListIntLonNam.append(swi_int.InterfaceName) for show_int_sw_per_int in listshowintswi: # through "sh interface switch" per interface intshortname = show_int_sw_per_int[0].split(":")[1].strip() self.Interfaces[intshortname].ShowInterfaceSwitchportPerInt = show_int_sw_per_int self.show_int_capabilities() dicshowintcap = netconparser.cut_include_from_list(self.ShowInterfaceCapabilities, self.ListIntLonNam) for key_int in self.Interfaces.keys(): # through all interfaces, key Interface_short_name int_holder = self.Interfaces[key_int] if int_holder.InterfaceName in dicshowintcap.keys(): self.Interfaces[key_int].ShowInterfaceCapabilitiesPerInt = dicshowintcap[int_holder.InterfaceName] if key_int in self.MacAddress.keys(): self.Interfaces[key_int].ListMacAddress = self.MacAddress[key_int] int_holder.load_interface_details() def configure_interfaces(self, list_interfaces, list_commands, debug=True): if debug: pass self.Device_Connection.enable() self.Device_Connection.config_mode() if debug: print("in \"conf t\" mode") for interface in list_interfaces: if debug: print("int "+interface) self.Device_Connection.send_config_set(["int "+interface]) self.Device_Connection.send_config_set(list_commands) self.Device_Connection.exit_config_mode() def reset_interfaces(self, list_interfaces, debug=True): self.list_commands = ["shutdown", "no shutdown"] self.configure_interfaces(list_interfaces, self.list_commands) if debug: print("reset :", list_interfaces) return def disable_interfaces(self, list_interfaces): self.list_commands = ["shutdown"] self.configure_interfaces(list_interfaces, self.list_commands) return def display_sh_ver_brief(self): # Working with the IOS version, getting it and presenting a brief. print("getting sh ver...") self.show_version() for line in self.ShowVersionBrief: print(line) print(self.SystemUpTime) print() def display_sh_modules(self): # for 6x00 platform. self.show_module() if len(self.ShowModule) > 0: if self.ShowModule[0].find("^") < 0: for line in self.ShowModule: print(line) def display_sh_vlan_brief(self): # Working with Vlans, getting them and presenting a brief. print("Populating vlans...") self.populate_vlans() vlansordered = list(self.Vlans.keys()) vlansordered.sort() for vlankey in vlansordered: line = netconparser.format_str_space([(self.Vlans[vlankey][0], 'r', 7), (self.Vlans[vlankey][1], 'l', 32), (self.Vlans[vlankey][2], 'l', 11)]) print(line) def show_int_steroids(self): self.display_sh_ver_brief() self.display_sh_modules() self.display_sh_vlan_brief() # Working with interfaces details, getting details from interfaces and producing a report; # we will use 'show interface status' as a base and add fields to the default output. print('Populating interfaces...') self.populate_interfaces() number_interfaces = 0 number_interface_used = 0 up_time_short = netconparser.uptime_to_short(self.SystemUpTime) for line_int_status in self.ShowInterfacesStatus: vlan = "" if len(line_int_status) > 0: interface_short = line_int_status.split()[0] base_t = False if interface_short in self.Interfaces.keys(): interface = interface_short # print(interface_short) description = self.Interfaces[interface_short].InterfaceDescription status = self.Interfaces[interface_short].LineProtocol.split()[-1] if self.Interfaces[interface_short].AdministrativeMode == "trunk": vlan = "trunk" elif self.Interfaces[interface_short].AdministrativeMode == "routed": vlan = "routed" else: vlan = self.Interfaces[interface_short].AccessModeVlan voice = self.Interfaces[interface_short].VoiceVlan inttype = self.Interfaces[interface_short].Type if inttype.find("10/100/1000BaseT") >= 0: number_interfaces += 1 base_t = True packetsIn = self.Interfaces[interface_short].PacketsInput packetsOut = self.Interfaces[interface_short].PacketsOutput if packetsIn or packetsOut > 0: used = 'Yes' if base_t: number_interface_used += 1 else: used = 'No' lastclearing = self.Interfaces[interface_short].LastClearing if lastclearing == 'never': lastclearing = up_time_short line = netconparser.format_str_space([(interface, 'l', 12), (description, 'l', 15), (status, 'r', 12), (vlan, 'r', 8), (voice, 'l', 8), (inttype, 'l', 20), (used, 'l', 4), (lastclearing, 'r', 15) ]) print(line) if len(self.Interfaces[interface_short].ListMacAddress) > 0 and \ self.Interfaces[interface_short].AdministrativeMode == "static access": for mac_entry in self.Interfaces[interface_short].ListMacAddress: line = netconparser.format_str_space([(' ', 'r', 65), (str(mac_entry), 'l', 30) ]) # print(mac_entry) print(line) print("Number of interfaces 10/100/1000BaseT: ", number_interfaces) print("Interfaces 10/100/1000BaseT in use: ", number_interface_used) print("Interfaces 10/100/1000BaseT spare: ", number_interfaces - number_interface_used) print("Percentage use of 10/100/1000BaseT: {:2.0%}".format(number_interface_used/number_interfaces)) print("\nFinished with: ", self.DeviceName) print("\n\n") return def show_int_steroids_adv(self): self.display_sh_ver_brief() self.display_sh_modules() self.display_sh_vlan_brief() # Working with interfaces details, getting details from interfaces and producing a report; # we will use 'show interface status' as a base and add fields to the default output. print('Populating interfaces...') self.populate_interfaces() number_interfaces = 0 number_interface_used = 0 up_time_short = netconparser.uptime_to_short(self.SystemUpTime) for line_int_status in self.ShowInterfacesStatus: vlan = "" if len(line_int_status) > 0: interface_short = line_int_status.split()[0] base_t = False if interface_short in self.Interfaces.keys(): interface = interface_short # print(interface_short) description = self.Interfaces[interface_short].InterfaceDescription status = self.Interfaces[interface_short].LineProtocol.split()[-1] if self.Interfaces[interface_short].AdministrativeMode == "trunk": vlan = "trunk" elif self.Interfaces[interface_short].AdministrativeMode == "routed": vlan = "routed" else: vlan = self.Interfaces[interface_short].AccessModeVlan voice = self.Interfaces[interface_short].VoiceVlan inttype = self.Interfaces[interface_short].Type if inttype.find("10/100/1000BaseT") >= 0: number_interfaces += 1 base_t = True packetsIn = self.Interfaces[interface_short].PacketsInput packetsOut = self.Interfaces[interface_short].PacketsOutput if packetsIn or packetsOut > 0: used = 'Yes' if base_t: number_interface_used += 1 else: used = 'No' lastclearing = self.Interfaces[interface_short].LastClearing if lastclearing == 'never': lastclearing = up_time_short line = netconparser.format_str_space([(interface, 'l', 12), (description, 'l', 15), (status, 'r', 12), (vlan, 'r', 8), (voice, 'l', 8), (inttype, 'l', 20), (used, 'l', 4), (lastclearing, 'r', 15) ]) print(line) if len(self.Interfaces[interface_short].ListMacAddress) > 0 and \ self.Interfaces[interface_short].AdministrativeMode == "static access": for mac_entry in self.Interfaces[interface_short].ListMacAddress: mac_vendor = QueryMac().mac_company(str(mac_entry)) line = netconparser.format_str_space([(' ', 'r', 65), (str(mac_entry), 'l', 30), (mac_vendor, 'l', 20) ]) # print(mac_entry) print(line) print("Number of interfaces 10/100/1000BaseT: ", number_interfaces) print("Interfaces 10/100/1000BaseT in use: ", number_interface_used) print("Percentage use of 10/100/1000BaseT: {:2.0%}".format(number_interface_used/number_interfaces)) print("Percentage use of 10/100/1000BaseT: {:2.0%}".format(number_interface_used/number_interfaces)) print("\nFinished with: ", self.DeviceName) print("\n") return
from getpass import getpass from datetime import datetime import time password = getpass(prompt="Bitte Passwort eingeben : ") cisco_ios4 = {"host": "cisco4.lasthop.io", "username": "******", "password": password, "device_type": "cisco_ios", "session_log": "my_session.txt", "secret": password} ios_connect = ConnectHandler(**cisco_ios4) print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.config_mode() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.exit_config_mode() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.write_channel("disable\n") print("Current prompt :" + str(ios_connect.find_prompt())) time.sleep(2) output = ios_connect.read_channel() print(output) ios_connect.enable() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.disconnect()
'device_type': 'cisco_ios', #device type from https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py 'host': '10.1.1.10', 'username': '******', 'password': '******', 'port': 22, # optional, default 22 'secret': 'cisco', # this is the enable password 'verbose': True # optional, default False } connection = ConnectHandler(**cisco_device) # getting the router's prompt prompt = connection.find_prompt() if '>' in prompt: connection.enable() # entering the enable mode output = connection.send_command('sh run') print(output) if not connection.check_config_mode( ): # returns True if it's already in the global config mode connection.config_mode() # entering the global config mode # print(connection.check_config_mode()) connection.send_command('username u3 secret cisco') connection.exit_config_mode() # exiting the global config mode print(connection.check_config_mode()) print('Closing connection') connection.disconnect()
class PANOSDriver(NetworkDriver): def __init__(self, hostname, username, password, timeout=60, optional_args=None): self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.loaded = False self.changed = False self.device = None self.ssh_device = None self.ssh_connection = False self.merge_config = False if optional_args is None: optional_args = {} netmiko_argument_map = { 'port': None, 'verbose': False, 'use_keys': False, 'key_file': None, 'ssh_strict': False, 'system_host_keys': False, 'alt_host_keys': False, 'alt_key_file': '', 'ssh_config_file': None, } fields = netmiko_version.split('.') fields = [int(x) for x in fields] maj_ver, min_ver, bug_fix = fields if maj_ver >= 2: netmiko_argument_map['allow_agent'] = False elif maj_ver == 1 and min_ver >= 1: netmiko_argument_map['allow_agent'] = False # Build dict of any optional Netmiko args self.netmiko_optional_args = {} for k, v in netmiko_argument_map.items(): try: self.netmiko_optional_args[k] = optional_args[k] except KeyError: pass self.api_key = optional_args.get('api_key', '') def open(self): try: if self.api_key: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_key=self.api_key) else: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_username=self.username, api_password=self.password) except ConnectionException as e: raise ConnectionException(str(e)) def _open_ssh(self): try: self.ssh_device = ConnectHandler(device_type='paloalto_panos', ip=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) except ConnectionException as e: raise ConnectionException(str(e)) self.ssh_connection = True def close(self): self.device = None if self.ssh_connection: self.ssh_device.disconnect() self.ssh_connection = False self.ssh_device = None def _import_file(self, filename): if not self.api_key: key = self.device.keygen() else: key = self.api_key params = { 'type': 'import', 'category': 'configuration', 'key': key } path = os.path.basename(filename) mef = requests_toolbelt.MultipartEncoder( fields={ 'file': (path, open(filename, 'rb'), 'application/octet-stream') } ) requests.packages.urllib3.disable_warnings(InsecureRequestWarning) url = 'https://{0}/api/'.format(self.hostname) request = requests.post( url, verify=False, params=params, headers={'Content-Type': mef.content_type}, data=mef ) # if something goes wrong just raise an exception request.raise_for_status() response = xml.etree.ElementTree.fromstring(request.content) if response.attrib['status'] == 'error': return False else: return path def is_alive(self): if self.device: if self.ssh_connection: is_alive = self.ssh_device.remote_conn.transport.is_active() else: is_alive = True else: is_alive = False return {'is_alive': is_alive} def load_replace_candidate(self, filename=None, config=None): if config: raise ReplaceConfigException("This method requires a config file.") elif filename: if self.loaded is False: if self._save_backup() is False: raise ReplaceConfigException('Error while storing backup config') path = self._import_file(filename) if path is False: msg = "Error while trying to move the config file to the device." raise ReplaceConfigException(msg) # Let's load the config. cmd = '<load><config><from>{0}</from></config></load>'.format(path) self.device.op(cmd=cmd) if self.device.status == 'success': self.loaded = True else: raise ReplaceConfigException('Error while loading config from {0}').format(path) else: raise ReplaceConfigException("This method requires a config file.") def _get_file_content(self, filename): try: with open(filename, 'r') as f: content = f.read() except IOError: raise MergeConfigException('Error while opening {0}. Make sure ' 'filename is correct.'.format(filename)) return content def _send_merge_commands(self, config, file_config): """ Netmiko is being used to push set commands. """ if self.loaded is False: if self._save_backup() is False: raise MergeConfigException('Error while storing backup ' 'config.') if self.ssh_connection is False: self._open_ssh() if file_config: if isinstance(config, str): config = config.splitlines() else: if isinstance(config, str): config = str(config).split() self.ssh_device.send_config_set(config) self.loaded = True self.merge_config = True def _get_candidate(self): candidate_command = '<show><config><candidate></candidate></config></show>' self.device.op(cmd=candidate_command) candidate = str(self.device.xml_root()) return candidate def _get_running(self): self.device.show() running = str(self.device.xml_root()) return running def get_config(self, retrieve='all'): configs = {} running = py23_compat.text_type('') candidate = py23_compat.text_type('') startup = py23_compat.text_type('') if retrieve == 'all': running = py23_compat.text_type(self._get_running()) candidate = py23_compat.text_type(self._get_candidate()) elif retrieve == 'running': running = py23_compat.text_type(self._get_running()) elif retrieve == 'candidate': candidate = py23_compat.text_type(self._get_candidate()) configs['running'] = running configs['candidate'] = candidate configs['startup'] = startup return configs def load_merge_candidate(self, filename=None, config=None): if filename: file_config = True content = self._get_file_content(filename) config = content.splitlines() self._send_merge_commands(config, file_config) elif config: file_config = False self._send_merge_commands(config, file_config) else: raise MergeConfigException('You must provide either a file ' 'or a set-format string') def compare_config(self): """ Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command. """ if self.ssh_connection is False: self._open_ssh() self.ssh_device.exit_config_mode() diff = self.ssh_device.send_command("show config diff") return diff.strip() def _save_backup(self): self.backup_file = 'config_{0}.xml'.format(str(datetime.now().date()).replace(' ', '_')) backup_command = '<save><config><to>{0}</to></config></save>'.format(self.backup_file) self.device.op(cmd=backup_command) if self.device.status == 'success': return True else: return False def commit_config(self): """ Netmiko is being used to commit the configuration because it takes a better care of results compared to pan-python. """ if self.loaded: if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() time.sleep(3) self.loaded = False self.changed = True except: # noqa if self.merge_config: raise MergeConfigException('Error while commiting config') else: raise ReplaceConfigException('Error while commiting config') else: raise ReplaceConfigException('No config loaded.') def discard_config(self): if self.loaded: discard_cmd = '<load><config><from>{0}</from></config></load>'.format(self.backup_file) self.device.op(cmd=discard_cmd) if self.device.status == 'success': self.loaded = False self.merge_config = False else: raise ReplaceConfigException("Error while loading backup config.") def rollback(self): """ Netmiko is being used to commit the rollback configuration because it takes a better care of results compared to pan-python. """ if self.changed: rollback_cmd = '<load><config><from>{0}</from></config></load>'.format(self.backup_file) self.device.op(cmd=rollback_cmd) time.sleep(5) if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() self.loaded = False self.changed = False self.merge_config = False except: # noqa ReplaceConfigException("Error while loading backup config") def _extract_interface_list(self): self.device.op(cmd='<show><interface>all</interface></show>') interfaces_xml = xmltodict.parse(self.device.xml_root()) interfaces_json = json.dumps(interfaces_xml['response']['result']) interfaces = json.loads(interfaces_json) interface_set = set() for entry in interfaces.values(): for entry_contents in entry.values(): if isinstance(entry_contents, dict): # If only 1 interface is listed, xmltodict returns a dictionary, otherwise # it returns a list of dictionaries. entry_contents = [entry_contents] for intf in entry_contents: interface_set.add(intf['name']) return list(interface_set) def get_facts(self): facts = {} try: self.device.op(cmd='<show><system><info></info></system></show>') system_info_xml = xmltodict.parse(self.device.xml_root()) system_info_json = json.dumps(system_info_xml['response']['result']['system']) system_info = json.loads(system_info_json) except AttributeError: system_info = {} if system_info: facts['hostname'] = system_info['hostname'] facts['vendor'] = py23_compat.text_type('Palo Alto Networks') facts['uptime'] = int(convert_uptime_string_seconds(system_info['uptime'])) facts['os_version'] = system_info['sw-version'] facts['serial_number'] = system_info['serial'] facts['model'] = system_info['model'] facts['fqdn'] = py23_compat.text_type('N/A') facts['interface_list'] = self._extract_interface_list() facts['interface_list'].sort() return facts def get_lldp_neighbors(self): """Return LLDP neighbors details.""" neighbors = {} cmd = '<show><lldp><neighbors>all</neighbors></lldp></show>' try: self.device.op(cmd=cmd) lldp_table_xml = xmltodict.parse(self.device.xml_root()) lldp_table_json = json.dumps(lldp_table_xml['response']['result']['entry']) lldp_table = json.loads(lldp_table_json) except AttributeError: lldp_table = [] for lldp_item in lldp_table: local_int = lldp_item['@name'] if local_int not in neighbors.keys(): neighbors[local_int] = [] try: lldp_neighs = lldp_item.get('neighbors').get('entry') except AttributeError: lldp_neighs = '' if isinstance(lldp_neighs, dict): lldp_neighs = [lldp_neighs] for neighbor in lldp_neighs: n = {} n['hostname'] = neighbor['system-name'] n['port'] = neighbor['port-id'] neighbors[local_int].append(n) return neighbors def get_route_to(self, destination='', protocol=''): """Return route details to a specific destination, learned from a certain protocol.""" # Note, it should be possible to query the FIB: # "<show><routing><fib></fib></routing></show>" # To add informations to this getter routes = {} if destination: destination = "<destination>{0}</destination>".format(destination) if protocol: protocol = "<type>{0}</type>".format(protocol) cmd = "<show><routing><route>{0}{1}</route></routing></show>".format(protocol, destination) try: self.device.op(cmd=cmd) routes_table_xml = xmltodict.parse(self.device.xml_root()) routes_table_json = json.dumps(routes_table_xml['response']['result']['entry']) routes_table = json.loads(routes_table_json) except (AttributeError, KeyError): routes_table = [] if isinstance(routes_table, dict): routes_table = [routes_table] for route in routes_table: d = { 'current_active': False, 'last_active': False, 'age': -1, 'next_hop': u'', 'protocol': u'', 'outgoing_interface': u'', 'preference': -1, 'inactive_reason': u'', 'routing_table': u'default', 'selected_next_hop': False, 'protocol_attributes': {} } destination = route['destination'] flags = route['flags'] if 'A' in flags: d['current_active'] = True else: d['current_active'] = False if 'C' in flags: d['protocol'] = "connect" if 'S' in flags: d['protocol'] = "static" if 'R' in flags: d['protocol'] = "rip" if 'R' in flags: d['protocol'] = "rip" if 'O' in flags: d['protocol'] = "ospf" if 'B' in flags: d['protocol'] = "bgp" if 'H' in flags: d['protocol'] = "host" if route['age'] is not None: d['age'] = int(route['age']) if route['nexthop'] is not None: d['next_hop'] = route['nexthop'] if route['interface'] is not None: d['outgoing_interface'] = route['interface'] if route['metric'] is not None: d['preference'] = int(route['metric']) if route['virtual-router'] is not None: d['routing_table'] = route['virtual-router'] if destination not in routes.keys(): routes[destination] = [] routes[destination].append(d) return routes def get_interfaces(self): LOOPBACK_SUBIF_DEFAULTS = { 'is_up': True, 'is_enabled': True, 'speed': 0, 'last_flapped': -1.0, 'mac_address': '', 'description': 'N/A' } interface_dict = {} interface_list = self._extract_interface_list() for intf in interface_list: interface = {} cmd = "<show><interface>{0}</interface></show>".format(intf) try: self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps(interface_info_xml['response']['result']['hw']) interface_info = json.loads(interface_info_json) except KeyError as err: if 'loopback.' in intf and 'hw' in str(err): # loopback sub-ifs don't return a 'hw' key interface_dict[intf] = LOOPBACK_SUBIF_DEFAULTS continue raise interface['is_up'] = interface_info.get('state') == 'up' conf_state = interface_info.get('state_c') if conf_state == 'down': interface['is_enabled'] = False elif conf_state in ('up', 'auto'): interface['is_enabled'] = True else: msg = 'Unknown configured state {} for interface {}'.format(conf_state, intf) raise RuntimeError(msg) interface['last_flapped'] = -1.0 interface['speed'] = interface_info.get('speed') # Loopback and down interfaces if interface['speed'] in ('[n/a]', 'unknown'): interface['speed'] = 0 else: interface['speed'] = int(interface['speed']) interface['mac_address'] = standardize_mac(interface_info.get('mac')) interface['description'] = py23_compat.text_type('N/A') interface_dict[intf] = interface return interface_dict def get_interfaces_ip(self): '''Return IP interface data.''' def extract_ip_info(parsed_intf_dict): ''' IPv4: - Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'. - Secondary IP's are in '<addr>'. If no secondaries, this field is not returned by the xmltodict.parse() method. IPv6: - All addresses are returned in '<addr6>'. If no v6 configured, this is not returned either by xmltodict.parse(). Example of XML response for an intf with multiple IPv4 and IPv6 addresses: <response status="success"> <result> <ifnet> <entry> <name>ethernet1/5</name> <zone/> <fwd>N/A</fwd> <vsys>1</vsys> <dyn-addr/> <addr6> <member>fe80::d61d:71ff:fed8:fe14/64</member> <member>2001::1234/120</member> </addr6> <tag>0</tag> <ip>169.254.0.1/30</ip> <id>20</id> <addr> <member>1.1.1.1/28</member> </addr> </entry> {...} </ifnet> <hw> {...} </hw> </result> </response> ''' intf = parsed_intf_dict['name'] _ip_info = {intf: {}} v4_ip = parsed_intf_dict.get('ip') secondary_v4_ip = parsed_intf_dict.get('addr') v6_ip = parsed_intf_dict.get('addr6') if v4_ip != 'N/A': address, pref = v4_ip.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)} if secondary_v4_ip is not None: members = secondary_v4_ip['member'] if not isinstance(members, list): # If only 1 secondary IP is present, xmltodict converts field to a string, else # it converts it to a list of strings. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)} if v6_ip is not None: members = v6_ip['member'] if not isinstance(members, list): # Same "1 vs many -> string vs list of strings" comment. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv6', {})[address] = {'prefix_length': int(pref)} # Reset dictionary if no addresses were found. if _ip_info == {intf: {}}: _ip_info = {} return _ip_info ip_interfaces = {} cmd = "<show><interface>all</interface></show>" self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps( interface_info_xml['response']['result']['ifnet']['entry'] ) interface_info = json.loads(interface_info_json) if isinstance(interface_info, dict): # Same "1 vs many -> dict vs list of dicts" comment. interface_info = [interface_info] for interface_dict in interface_info: ip_info = extract_ip_info(interface_dict) if ip_info: ip_interfaces.update(ip_info) return ip_interfaces
class PANOSDriver(NetworkDriver): def __init__(self, hostname, username, password, timeout=60, optional_args=None): self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.loaded = False self.changed = False self.device = None self.ssh_device = None self.ssh_connection = False self.merge_config = False if optional_args is None: optional_args = {} netmiko_argument_map = { 'port': None, 'verbose': False, 'use_keys': False, 'key_file': None, 'ssh_strict': False, 'system_host_keys': False, 'alt_host_keys': False, 'alt_key_file': '', 'ssh_config_file': None, } fields = netmiko_version.split('.') fields = [int(x) for x in fields] maj_ver, min_ver, bug_fix = fields if maj_ver >= 2: netmiko_argument_map['allow_agent'] = False elif maj_ver == 1 and min_ver >= 1: netmiko_argument_map['allow_agent'] = False # Build dict of any optional Netmiko args self.netmiko_optional_args = {} for k, v in netmiko_argument_map.items(): try: self.netmiko_optional_args[k] = optional_args[k] except KeyError: pass self.api_key = optional_args.get('api_key', '') def open(self): try: if self.api_key: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_key=self.api_key) else: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_username=self.username, api_password=self.password) except ConnectionException as e: raise ConnectionException(str(e)) def _open_ssh(self): try: self.ssh_device = ConnectHandler(device_type='paloalto_panos', ip=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) except ConnectionException as e: raise ConnectionException(str(e)) self.ssh_connection = True def close(self): self.device = None if self.ssh_connection: self.ssh_device.disconnect() self.ssh_connection = False self.ssh_device = None def _import_file(self, filename): if not self.api_key: key = self.device.keygen() else: key = self.api_key params = {'type': 'import', 'category': 'configuration', 'key': key} path = os.path.basename(filename) mef = requests_toolbelt.MultipartEncoder(fields={ 'file': (path, open(filename, 'rb'), 'application/octet-stream') }) requests.packages.urllib3.disable_warnings(InsecureRequestWarning) url = 'https://{0}/api/'.format(self.hostname) request = requests.post(url, verify=False, params=params, headers={'Content-Type': mef.content_type}, data=mef) # if something goes wrong just raise an exception request.raise_for_status() response = xml.etree.ElementTree.fromstring(request.content) if response.attrib['status'] == 'error': return False else: return path def is_alive(self): if self.device: if self.ssh_connection: is_alive = self.ssh_device.remote_conn.transport.is_active() else: is_alive = True else: is_alive = False return {'is_alive': is_alive} def load_replace_candidate(self, filename=None, config=None): if config: raise ReplaceConfigException("This method requires a config file.") elif filename: if self.loaded is False: if self._save_backup() is False: raise ReplaceConfigException( 'Error while storing backup config') path = self._import_file(filename) if path is False: msg = "Error while trying to move the config file to the device." raise ReplaceConfigException(msg) # Let's load the config. cmd = '<load><config><from>{0}</from></config></load>'.format(path) self.device.op(cmd=cmd) if self.device.status == 'success': self.loaded = True else: raise ReplaceConfigException( 'Error while loading config from {0}').format(path) else: raise ReplaceConfigException("This method requires a config file.") def _get_file_content(self, filename): try: with open(filename, 'r') as f: content = f.read() except IOError: raise MergeConfigException('Error while opening {0}. Make sure ' 'filename is correct.'.format(filename)) return content def _send_merge_commands(self, config, file_config): """ Netmiko is being used to push set commands. """ if self.loaded is False: if self._save_backup() is False: raise MergeConfigException('Error while storing backup ' 'config.') if self.ssh_connection is False: self._open_ssh() if file_config: if isinstance(config, str): config = config.splitlines() else: if isinstance(config, str): config = str(config).split() self.ssh_device.send_config_set(config) self.loaded = True self.merge_config = True def _get_candidate(self): candidate_command = '<show><config><candidate></candidate></config></show>' self.device.op(cmd=candidate_command) candidate = str(self.device.xml_root()) return candidate def _get_running(self): self.device.show() running = str(self.device.xml_root()) return running def get_config(self, retrieve='all'): configs = {} running = py23_compat.text_type('') candidate = py23_compat.text_type('') startup = py23_compat.text_type('') if retrieve == 'all': running = py23_compat.text_type(self._get_running()) candidate = py23_compat.text_type(self._get_candidate()) elif retrieve == 'running': running = py23_compat.text_type(self._get_running()) elif retrieve == 'candidate': candidate = py23_compat.text_type(self._get_candidate()) configs['running'] = running configs['candidate'] = candidate configs['startup'] = startup return configs def load_merge_candidate(self, filename=None, config=None): if filename: file_config = True content = self._get_file_content(filename) config = content.splitlines() self._send_merge_commands(config, file_config) elif config: file_config = False self._send_merge_commands(config, file_config) else: raise MergeConfigException('You must provide either a file ' 'or a set-format string') def compare_config(self): """ Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command. """ if self.ssh_connection is False: self._open_ssh() self.ssh_device.exit_config_mode() diff = self.ssh_device.send_command("show config diff") return diff.strip() def _save_backup(self): self.backup_file = 'config_{0}.xml'.format( str(datetime.now().date()).replace(' ', '_')) backup_command = '<save><config><to>{0}</to></config></save>'.format( self.backup_file) self.device.op(cmd=backup_command) if self.device.status == 'success': return True else: return False def commit_config(self): """ Netmiko is being used to commit the configuration because it takes a better care of results compared to pan-python. """ if self.loaded: if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() time.sleep(3) self.loaded = False self.changed = True except: # noqa if self.merge_config: raise MergeConfigException('Error while commiting config') else: raise ReplaceConfigException( 'Error while commiting config') else: raise ReplaceConfigException('No config loaded.') def discard_config(self): if self.loaded: discard_cmd = '<load><config><from>{0}</from></config></load>'.format( self.backup_file) self.device.op(cmd=discard_cmd) if self.device.status == 'success': self.loaded = False self.merge_config = False else: raise ReplaceConfigException( "Error while loading backup config.") def rollback(self): """ Netmiko is being used to commit the rollback configuration because it takes a better care of results compared to pan-python. """ if self.changed: rollback_cmd = '<load><config><from>{0}</from></config></load>'.format( self.backup_file) self.device.op(cmd=rollback_cmd) time.sleep(5) if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() self.loaded = False self.changed = False self.merge_config = False except: # noqa ReplaceConfigException("Error while loading backup config") def get_facts(self): facts = {} try: self.device.op(cmd='<show><system><info></info></system></show>') system_info_xml = xmltodict.parse(self.device.xml_root()) system_info_json = json.dumps( system_info_xml['response']['result']['system']) system_info = json.loads(system_info_json) except AttributeError: system_info = {} try: self.device.op(cmd='<show><interface>all</interface></show>') interfaces_xml = xmltodict.parse(self.device.xml_root()) interfaces_json = json.dumps(interfaces_xml['response']['result']) interfaces = json.loads(interfaces_json) except AttributeError: interfaces = {} if system_info: facts['hostname'] = system_info['hostname'] facts['vendor'] = py23_compat.text_type('Palo Alto Networks') facts['uptime'] = int( convert_uptime_string_seconds(system_info['uptime'])) facts['os_version'] = system_info['sw-version'] facts['serial_number'] = system_info['serial'] facts['model'] = system_info['model'] facts['fqdn'] = py23_compat.text_type('N/A') facts['interface_list'] = [] for element in interfaces: for entry in interfaces[element]: for intf in interfaces[element][entry]: if intf['name'] not in facts['interface_list']: facts['interface_list'].append(intf['name']) facts['interface_list'].sort() return facts def get_lldp_neighbors(self): """Return LLDP neighbors details.""" neighbors = {} cmd = '<show><lldp><neighbors>all</neighbors></lldp></show>' try: self.device.op(cmd=cmd) lldp_table_xml = xmltodict.parse(self.device.xml_root()) lldp_table_json = json.dumps( lldp_table_xml['response']['result']['entry']) lldp_table = json.loads(lldp_table_json) except AttributeError: lldp_table = [] for lldp_item in lldp_table: local_int = lldp_item['@name'] if local_int not in neighbors.keys(): neighbors[local_int] = [] try: lldp_neighs = lldp_item.get('neighbors').get('entry') except AttributeError: lldp_neighs = '' if isinstance(lldp_neighs, dict): lldp_neighs = [lldp_neighs] for neighbor in lldp_neighs: n = {} n['hostname'] = neighbor['system-name'] n['port'] = neighbor['port-id'] neighbors[local_int].append(n) return neighbors def get_route_to(self, destination='', protocol=''): """Return route details to a specific destination, learned from a certain protocol.""" # Note, it should be possible to query the FIB: # "<show><routing><fib></fib></routing></show>" # To add informations to this getter routes = {} if destination: destination = "<destination>{0}</destination>".format(destination) if protocol: protocol = "<type>{0}</type>".format(protocol) cmd = "<show><routing><route>{0}{1}</route></routing></show>".format( protocol, destination) try: self.device.op(cmd=cmd) routes_table_xml = xmltodict.parse(self.device.xml_root()) routes_table_json = json.dumps( routes_table_xml['response']['result']['entry']) routes_table = json.loads(routes_table_json) except (AttributeError, KeyError): routes_table = [] if isinstance(routes_table, dict): routes_table = [routes_table] for route in routes_table: d = { 'current_active': False, 'last_active': False, 'age': -1, 'next_hop': u'', 'protocol': u'', 'outgoing_interface': u'', 'preference': -1, 'inactive_reason': u'', 'routing_table': u'default', 'selected_next_hop': False, 'protocol_attributes': {} } destination = route['destination'] flags = route['flags'] if 'A' in flags: d['current_active'] = True else: d['current_active'] = False if 'C' in flags: d['protocol'] = "connect" if 'S' in flags: d['protocol'] = "static" if 'R' in flags: d['protocol'] = "rip" if 'R' in flags: d['protocol'] = "rip" if 'O' in flags: d['protocol'] = "ospf" if 'B' in flags: d['protocol'] = "bgp" if 'H' in flags: d['protocol'] = "host" if route['age'] is not None: d['age'] = int(route['age']) if route['nexthop'] is not None: d['next_hop'] = route['nexthop'] if route['interface'] is not None: d['outgoing_interface'] = route['interface'] if route['metric'] is not None: d['preference'] = int(route['metric']) if route['virtual-router'] is not None: d['routing_table'] = route['virtual-router'] if destination not in routes.keys(): routes[destination] = [] routes[destination].append(d) return routes def get_interfaces(self): interface_dict = {} interface_list = self.get_facts()['interface_list'] for intf in interface_list: interface = {} cmd = "<show><interface>{0}</interface></show>".format(intf) try: self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps( interface_info_xml['response']['result']['hw']) interface_info = json.loads(interface_info_json) except AttributeError: interface_info = {} name = interface_info.get('name') state = interface_info.get('state') if state == 'up': interface['is_up'] = True interface['is_enabled'] = True else: interface['is_up'] = False interface['is_enabled'] = False interface['last_flapped'] = -1.0 interface['speed'] = interface_info.get('speed') # Quick fix for loopback interfaces if interface['speed'] == '[n/a]': interface['speed'] = 0 else: interface['speed'] = int(interface['speed']) interface['mac_address'] = interface_info.get('mac') interface['description'] = py23_compat.text_type('N/A') interface_dict[name] = interface return interface_dict
#!/usr/bin/env python '''Script uses Netmiko to connect to router and enter config mode''' #### import statements from netmiko import ConnectHandler from device_list import ROUTER_LIST #### functions # main function (this is the main execution code for your program) def main(): '''Main function, opens connection, enters config mode, changes logging and verifies''' for a_device in ROUTER_LIST: a_connection = ConnectHandler(**a_device) a_connection.config_mode() if a_connection.check_config_mode(): a_connection.send_config_from_file(config_file='some_commands.txt') a_connection.exit_config_mode() output = a_connection.send_command("show run | include logging") print output else: print "We are NOT in Config mode" if __name__ == "__main__": # program execution starts here main() # first action is to call main function
# ------------------------------------ # # ------ show command ---------------- # # ------------------------------------ # output = device.send_command('show version') print output; # -------------------------------------------- # # ------ send config command - one by one ---- # # -------------------------------------------- # device.config_mode() device.send_command('interface fast1/0') device.send_command('ip addr 10.10.10.10 255.255.255.0') device.exit_config_mode() # --------------------------------------------- # # ------ send config command - multiple ------- # # --------------------------------------------- # commands = ['interface fa1/0', 'no shut'] device.send_config_set(commands) # --------------------------------------------- # # ------ send command to multiple devices ----- # # --------------------------------------------- # # First, define the networking devices:
def connect_ssh(device_dict, commands_set, cmd_exec_logic, fileno=None): ''' Connect to device and execute command list !!! tested for cisco_ios!!! Arg: devices: parameters of device (dict) queue: list of result commands_set: list of commands cmd_exec_logic: logic of execution ''' # We need to copy dict in list of command (create new object), otherwise we will get last commands set (result) for all nodes (change same object of commands) if not fileno == None: sys.stdin = os.fdopen(fileno) commands = copy.deepcopy(commands_set) queue = {} nodename = device_dict.get('nodename') del (device_dict['nodename']) print("%s[%s]%s Connection to device %s" % (bcolors.HEADER, nodename, bcolors.ENDC, device_dict['ip'])) logging.info("Connection to device %s" % device_dict['ip']) try: ssh = ConnectHandler(**device_dict) except Exception as e: logging.debug('\nConnect failed! {}'.format(e)) print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Connect failed! {1}'. format(nodename, e)) logging.info("Stop executing commands") print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Stop executing commands' .format(nodename)) failed_dic = [{'cmdname': 'Err', 'output': str(e), 'search': ''}] queue[nodename] = failed_dic return queue ssh.enable() for cmd_index, command in enumerate(commands): logging.debug('\n $command=:\n{} '.format(pformat(command))) #Checking command if command.get('command') == None: logging.debug( '\nSomething wrong in command syntax\'s! Incoming config for current command:\n{} ' .format(pformat(command.get('command')))) print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Something wrong in command syntax\'s! Incoming config for current command:\n{1} ' .format(nodename, pformat(command.get('command')))) logging.info("Stop executing commands") print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Stop executing commands' .format(nodename)) failed_dic = [{ 'cmdname': 'Err', 'output': 'Something wrong in command syntax', 'search': '' }] queue[nodename] = failed_dic return queue cmd = '' cmd_list = [] cmd_var_search = [] #build-in variables cmd_var_search = re.findall('\{\}', command.get('command')) command['command'] = re.sub('\{nodename\}', nodename, command.get('command')) command['command'] = re.sub('\{nodeip\}', device_dict['ip'], command.get('command')) command['command'] = re.sub('\{datetime\}', time.strftime("%Y%m%d%H%M%S"), command.get('command')) command['command'] = re.sub('\{date\}', time.strftime("%Y%m%d"), command.get('command')) command['search'] = re.sub('\{nodename\}', nodename, command.get('search')) command['search'] = re.sub('\{nodeip\}', device_dict['ip'], command.get('search')) command['search'] = re.sub('\{datetime\}', time.strftime("%Y%m%d%H%M%S"), command.get('search')) command['search'] = re.sub('\{date\}', time.strftime("%Y%m%d"), command.get('search')) command['device_type'] = device_dict['device_type'] if command.get('delay_factor') == '': logging.debug("set def delay_factor") command['delay_factor'] = '1' if cmd_var_search: result = re.findall(commands[cmd_index - 1].get('search'), commands[cmd_index - 1].get('output')) if result: cmd_parrent = command.get('command') for var_index, var in enumerate(result): cmd = cmd_parrent.format(var) if var_index == 0: commands[cmd_index]['command'] = cmd else: cmd_dic = {} cmd_dic = command.copy() cmd_dic['command'] = cmd cmd_dic['cmdname'] = cmd_dic.get( 'cmdname') + '(' + str(var_index) + ')' commands.insert(cmd_index + var_index, cmd_dic) logging.debug('\nNew command list:\n' + pformat(commands)) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break cmd_varlist_search = [] cmd_varlist_search = re.findall('\{\$\S+\}', command.get('command')) if cmd_varlist_search: table = get_result(commands[cmd_index - 1]) #check if result is list and not empty if len(table) >= 2 and type(table) == list: cmd_parrent = command.get('command') for varline_index, varline in enumerate(table): if varline_index == 0: continue new_cmd = cmd_parrent for var_index, var in enumerate(varline): if var_index == 0: continue new_cmd = re.sub('\{\$' + table[0][var_index] + '\}', var, new_cmd) if varline_index == 1: commands[cmd_index]['command'] = new_cmd else: cmd_dic = {} cmd_dic = command.copy() cmd_dic['command'] = new_cmd cmd_dic['cmdname'] = cmd_dic.get( 'cmdname') + '(' + str(varline_index) + ')' commands.insert(cmd_index + varline_index, cmd_dic) logging.debug('\nNew command list:\n' + pformat(commands)) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break print("%s[%s]%s Try to execute command: %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info("Try to execute command: %s on device: %s:" % (command.get('command'), device_dict['ip'])) cmd = command.get('command') if command.get('cmd_type') == 'usr_req': usr_req = raw_input('{}[{}]{} {}{}{}'.format( bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, command.get('command'), bcolors.ENDC)) commands[cmd_index + 1]['search'] = re.sub( '\{usr_req\}', usr_req, commands[cmd_index + 1]['search']) commands[cmd_index]['output'] = usr_req commands[cmd_index]['search'] = usr_req commands[cmd_index]['search_type'] = 'simple' if command.get('cmd_type') == 'choose_req': print('{}[{}]{} {}{}{}'.format(bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, command.get('command'), bcolors.ENDC)) table = get_result(commands[cmd_index - 1]) if len(table) >= 2: print(tabulate(table, headers='firstrow', tablefmt="pipe")) while True: usr_input = raw_input( '{}[{}]{} {}Enter number of line:{}'.format( bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, bcolors.ENDC)) try: usr_input = int(usr_input) except: print( '{}[{}]{} {}Entered not number of line, please enter number{}' .format(bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, bcolors.ENDC)) continue if usr_input in range(0, len(table) - 1): break else: print('{}Enter number of line in range {}{}'.format( bcolors.WARNING, range(0, len(table) - 1), bcolors.ENDC)) var_dict = dict(zip(table[0], table[usr_input + 1])) for var in var_dict: if var == 'N': continue commands[cmd_index + 1]['command'] = re.sub( '\{' + str(var) + '\}', var_dict.get(var), commands[cmd_index + 1]['command']) command['output'] = str(usr_input) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break if command.get('command') == 'timeout': print("%s[%s]%s Start timeout of executing script: %s" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('delay_factor'))) time.sleep(int(command.get('delay_factor'))) command['output'] = 'Timeout: %ssec' % ( command.get('delay_factor')) print("%s[%s]%s Continue executing script" % ( bcolors.HEADER, nodename, bcolors.ENDC, )) if command.get('command') == 'enter': cmd = '\n' if command.get( 'cmd_type') == 'conf_tpl' and not command.get('command') == '': command['command'] = parce_node_conf_template(nodename, command) command['cmd_type'] = 'conf_set' if command.get('cmd_type') == 'conf_enter': command['output'] = ssh.config_mode() elif command.get('cmd_type') == 'conf_exit': command['output'] = ssh.exit_config_mode() elif command.get('cmd_type') == 'conf_set': cmd_list = command.get('command').split(',') #for debug #print ('Find prompt is %s' % (ssh.find_prompt())) #prompt = ssh.send_command('\n', strip_prompt = False, strip_command = False, expect_string = '.*', auto_find_prompt=False) #print ('Current prompt is %s' % (prompt)) ssh.set_base_prompt() command['output'] = ssh.send_config_set( cmd_list, strip_prompt=False, strip_command=False, delay_factor=int(command.get( 'delay_factor'))) #.encode('ascii').decode('utf-8') elif command.get('cmd_type') == 'os_exec': cmd = re.sub('\<\>', check_output(commands[cmd_index - 1]), command.get('command')) #result = re.findall(commands[cmd_index-1].get('search'), commands[cmd_index-1].get('output')) #cmd = re.sub('\<\>', tabulate(result, headers=re.findall('P<(\w+)>', commands[cmd_index-1].get('search')), tablefmt='html'), command.get('command')) cmd = re.sub('\{command\}', commands[cmd_index - 1].get('command'), cmd) cmd = re.sub('\{nodename\}', nodename, cmd) cmd = re.sub('\{ip\}', device_dict['ip'], cmd) cmd = re.sub('\n', '\n\r', cmd) #print (cmd) command['output'] = sp.check_output(cmd, shell=True) elif command.get('output') == None: #print (ssh.find_prompt()) #print command.get('expect') current_prompt = '.*' if not command.get('expect'): try: current_prompt = ssh.find_prompt() logging.debug('Current prompt is %s' % (ssh.find_prompt())) except Exception as e: logging.debug('\nUnable to find prompt! {}'.format(e)) #print('\n[{0}] Unable to find prompt! {1}'.format(nodename, e)) expect_prompt = get_expect_string(command, current_prompt, device_dict['device_type']) if expect_prompt == "": try: command['output'] = ssh.send_command( cmd, strip_prompt=False, strip_command=False, delay_factor=int(command.get('delay_factor'))) #. except Exception as e: logging.debug('\nError {}'.format(e)) print('\n{}[{}]{} Error {}'.format( bcolors.HEADER, nodename, bcolors.ENDC, e)) break else: expect_prompt = command.get('expect') logging.debug('Expect prompt = %s' % (expect_prompt)) try: command['output'] = ssh.send_command( cmd, strip_prompt=False, strip_command=False, delay_factor=int(command.get('delay_factor')), expect_string=expect_prompt, auto_find_prompt=False) #.encode('ascii').decode('utf-8') except Exception as e: logging.debug('\nError! {}'.format(e)) print('\n{}[{}]{} Error {}'.format(bcolors.HEADER, nodename, bcolors.ENDC, e)) break logging.info("Checking executing commands logic:") if cmd_exec_logic.get('cmd_exec_err_logic') or cmd_exec_logic.get( 'cmd_exec_searchfail_logic'): print('{}[{}]{} Check command {} for error'.format( bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'))) result = chech_fail_exec(command, cmd_exec_logic) if result: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break logging.info("Command: %s on device: %s executed successfully" % (command.get('command'), device_dict['ip'])) if command.get('cmd_type') == 'conf_set': print( "%s[%s]%s Command: \n%s\n on device: %s executed successfully" % (bcolors.HEADER, nodename, bcolors.ENDC, re.sub(',', '\n', command.get('command')), device_dict['ip'])) else: print( "%s[%s]%s Command: %s on device: %s executed successfully" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) #add report logic, split search_type if len(command.get('search_type').split(',')) > 1: command['search_type'] = command.get('search_type').split(',')[0] command['last_val'] = 'last' queue[nodename] = commands logging.debug('\nEnd working whith node, result:\n{} '.format( pformat(queue))) try: if not fileno == None: os.close(fileno) except Exception as e: logging.debug('\nClose failed! {}'.format(e)) return queue
from netmiko import ConnectHandler pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': '******', } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() pynet_rtr2.check_config_mode() pynet_rtr2.exit_config_mode() pynet_rtr2.disconnect()
#This uses makes the connection to the network devices defined. #the ** is used to help pass all the dictionary information alone rtr1 = ConnectHandler(**pynetrtr1) rtr2 = ConnectHandler(**pynetrtr2) srx = ConnectHandler(**juniper_srx) #this output will confirm that the connection was made with netmiko and the ssh information used to make the connection print rtr1 print rtr2 print srx #this will place rtr2 into config mode and will display the output to confirm we are in that mode. rtr2.config_mode() outp_config = rtr2.find_prompt() print outp_config rtr2.exit_config_mode() #This will display the arp table for all three devices outp_rtr1 = rtr1.send_command("show arp") outp_rtr2 = rtr2.send_command("show arp") outp_srx = srx.send_command("show arp") outp_prompt = rtr1.find_prompt() print outp_prompt print outp_rtr1 outp_prompt = rtr2.find_prompt() print outp_prompt print outp_rtr2 output_prompt = srx.find_prompt() print outp_prompt
class VyOSDriver(NetworkDriver): _MINUTE_SECONDS = 60 _HOUR_SECONDS = 60 * _MINUTE_SECONDS _DAY_SECONDS = 24 * _HOUR_SECONDS _WEEK_SECONDS = 7 * _DAY_SECONDS _YEAR_SECONDS = 365 * _DAY_SECONDS _DEST_FILENAME = "/var/tmp/candidate_running.conf" _BACKUP_FILENAME = "/var/tmp/backup_running.conf" _BOOT_FILENAME = "/config/config.boot" def __init__(self, hostname, username, password, timeout=60, optional_args=None): self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.device = None self._scp_client = None self._new_config = None self._old_config = None self._ssh_usekeys = False # Netmiko possible arguments netmiko_argument_map = { 'port': None, 'secret': '', 'verbose': False, '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, } fields = netmiko_version.split('.') fields = [int(x) for x in fields] maj_ver, min_ver, bug_fix = fields if maj_ver >= 2: netmiko_argument_map['allow_agent'] = False elif maj_ver == 1 and min_ver >= 1: netmiko_argument_map['allow_agent'] = False # Build dict of any optional Netmiko args self.netmiko_optional_args = {} if optional_args is not None: for k, v in netmiko_argument_map.items(): try: self.netmiko_optional_args[k] = optional_args[k] except KeyError: pass self.global_delay_factor = optional_args.get( 'global_delay_factor', 1) self.port = optional_args.get('port', 22) def open(self): self.device = ConnectHandler(device_type='vyos', host=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) try: self._scp_client = SCPConn(self.device) except: raise ConnectionException("Failed to open connection ") def close(self): self.device.disconnect() def is_alive(self): """Returns a flag with the state of the SSH connection.""" return {'is_alive': self.device.remote_conn.transport.is_active()} def load_replace_candidate(self, filename=None, config=None): """ Only configuration files are supported with load_replace_candidate. It must be a full config file like /config/config.boot Due to the OS nature, we do not support a replace using a configuration string. """ if not filename and not config: raise ReplaceConfigException( 'filename or config param must be provided.') if filename is None: temp_file = tempfile.NamedTemporaryFile() temp_file.write(config) temp_file.flush() cfg_filename = temp_file.name else: cfg_filename = filename if os.path.exists(cfg_filename) is True: self._scp_client.scp_transfer_file(cfg_filename, self._DEST_FILENAME) self.device.send_command("cp " + self._BOOT_FILENAME + " " + self._BACKUP_FILENAME) output_loadcmd = self.device.send_config_set( ['load ' + self._DEST_FILENAME]) match_loaded = re.findall("Load complete.", output_loadcmd) match_notchanged = re.findall("No configuration changes to commit", output_loadcmd) match_failed = re.findall("Failed to parse specified config file", output_loadcmd) if match_failed: raise ReplaceConfigException("Failed replace config: " + output_loadcmd) if not match_loaded: if not match_notchanged: raise ReplaceConfigException("Failed replace config: " + output_loadcmd) else: raise ReplaceConfigException("config file is not found") def load_merge_candidate(self, filename=None, config=None): """ Only configuration in set-format is supported with load_merge_candidate. """ if not filename and not config: raise MergeConfigException( 'filename or config param must be provided.') if filename is None: temp_file = tempfile.NamedTemporaryFile() temp_file.write(config) temp_file.flush() cfg_filename = temp_file.name else: cfg_filename = filename if os.path.exists(cfg_filename) is True: with open(cfg_filename) as f: self.device.send_command("cp " + self._BOOT_FILENAME + " " + self._BACKUP_FILENAME) self._new_config = f.read() cfg = [x for x in self._new_config.split("\n") if x is not ""] output_loadcmd = self.device.send_config_set(cfg) match_setfailed = re.findall("Delete failed", output_loadcmd) match_delfailed = re.findall("Set failed", output_loadcmd) if match_setfailed or match_delfailed: raise MergeConfigException("Failed merge config: " + output_loadcmd) else: raise MergeConfigException("config file is not found") def discard_config(self): self.device.exit_config_mode() def compare_config(self): output_compare = self.device.send_config_set(['compare']) match = re.findall( "No changes between working and active configurations", output_compare) if match: return "" else: diff = ''.join(output_compare.splitlines(True)[1:-1]) return diff def commit_config(self, message=""): if message: raise NotImplementedError( "Commit message not implemented for this platform") try: self.device.commit() except ValueError: raise CommitError("Failed to commit config on the device") self.device.send_config_set(['save']) self.device.exit_config_mode() def rollback(self): """Rollback configuration to filename or to self.rollback_cfg file.""" filename = None if filename is None: filename = self._BACKUP_FILENAME output_loadcmd = self.device.send_config_set(['load ' + filename]) match = re.findall("Load complete.", output_loadcmd) if not match: raise ReplaceConfigException("Failed rollback config: " + output_loadcmd) else: self.device.send_config_set(['commit', 'save']) def get_environment(self): """ 'vmstat' output: procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- r b swpd free buff cache si so bi bo in cs us sy id wa 0 0 0 61404 139624 139360 0 0 0 0 9 14 0 0 100 0 """ output_cpu_list = list() output_cpu = self.device.send_command("vmstat") output_cpu = str(output_cpu) output_cpu_list = output_cpu.split("\n") if len(output_cpu_list[-1]) > 0: output_cpu_list = output_cpu_list[-1] else: output_cpu_list = output_cpu_list[-2] output_cpu_idle = output_cpu_list.split()[-2] cpu = 100 - int(output_cpu_idle) """ 'free' output: total used free shared buffers cached Mem: 508156 446784 61372 0 139624 139360 -/+ buffers/cache: 167800 340356 Swap: 0 0 0 """ output_ram = self.device.send_command("free").split("\n")[1] available_ram, used_ram = output_ram.split()[1:3] environment = { "fans": { "invalid": { "status": False } }, "temperature": { "invalid": { "temperature": 0.0, "is_alert": False, "is_critical": False } }, "power": { "invalid": { "status": True, "capacity": 0.0, "output": 0.0 } }, "cpu": { "0": { "%usage": float(cpu) }, }, "memory": { "available_ram": int(available_ram), "used_ram": int(used_ram) } } return environment def get_interfaces(self): """ "show interfaces" output example: Interface IP Address S/L Description --------- ---------- --- ----------- br0 - u/D eth0 192.168.1.1/24 u/u Management eth1 192.168.1.2/24 u/u eth2 192.168.3.1/24 u/u foobar 192.168.2.2/24 lo 127.0.0.1/8 u/u ::1/128 """ output_iface = self.device.send_command("show interfaces") # Collect all interfaces' name and status match = re.findall("(\S+)\s+[:\-\d/\.]+\s+([uAD])/([uAD])", output_iface) # 'match' example: # [("br0", "u", "D"), ("eth0", "u", "u"), ("eth1", "u", "u")...] iface_state = { iface_name: { "State": state, "Link": link } for iface_name, state, link in match } output_conf = self.device.send_command("show configuration") # Convert the configuration to dictionary config = vyattaconfparser.parse_conf(output_conf) iface_dict = dict() for iface_type in config["interfaces"]: ifaces_detail = config["interfaces"][iface_type] for iface_name in ifaces_detail: description = self._get_value("description", ifaces_detail[iface_name]) if description is None: description = "" speed = self._get_value("speed", ifaces_detail[iface_name]) if speed is None: speed = 0 if speed == "auto": speed = 0 hw_id = self._get_value("hw-id", ifaces_detail[iface_name]) if hw_id is None: hw_id = "00:00:00:00:00:00" is_up = (iface_state[iface_name]["Link"] == "u") is_enabled = (iface_state[iface_name]["State"] == "u") iface_dict.update({ iface_name: { "is_up": bool(is_up), "is_enabled": bool(is_enabled), "description": py23_compat.text_type(description), "last_flapped": float(-1), "speed": int(speed), "mac_address": py23_compat.text_type(hw_id) } }) return iface_dict @staticmethod def _get_value(key, target_dict): if key in target_dict: return target_dict[key] else: return None def get_arp_table(self, vrf=""): # 'age' is not implemented yet """ 'show arp' output example: Address HWtype HWaddress Flags Mask Iface 10.129.2.254 ether 00:50:56:97:af:b1 C eth0 192.168.1.134 (incomplete) eth1 192.168.1.1 ether 00:50:56:ba:26:7f C eth1 10.129.2.97 ether 00:50:56:9f:64:09 C eth0 192.168.1.3 ether 00:50:56:86:7b:06 C eth1 """ if vrf: raise NotImplementedError( "VRF support has not been added for this getter on this platform." ) output = self.device.send_command("show arp") output = output.split("\n") # Skip the header line output = output[1:-1] arp_table = list() for line in output: line = line.split() # 'line' example: # ["10.129.2.254", "ether", "00:50:56:97:af:b1", "C", "eth0"] # [u'10.0.12.33', u'(incomplete)', u'eth1'] if "incomplete" in line[1]: macaddr = py23_compat.text_type("00:00:00:00:00:00") else: macaddr = py23_compat.text_type(line[2]) arp_table.append({ 'interface': py23_compat.text_type(line[-1]), 'mac': macaddr, 'ip': py23_compat.text_type(line[0]), 'age': 0.0 }) return arp_table def get_ntp_stats(self): """ 'ntpq -np' output example remote refid st t when poll reach delay offset jitter ============================================================================== 116.91.118.97 133.243.238.244 2 u 51 64 377 5.436 987971. 1694.82 219.117.210.137 .GPS. 1 u 17 64 377 17.586 988068. 1652.00 133.130.120.204 133.243.238.164 2 u 46 64 377 7.717 987996. 1669.77 """ output = self.device.send_command("ntpq -np") output = output.split("\n")[2:] ntp_stats = list() for ntp_info in output: if len(ntp_info) > 0: remote, refid, st, t, when, hostpoll, reachability, delay, offset, \ jitter = ntp_info.split() # 'remote' contains '*' if the machine synchronized with NTP server synchronized = "*" in remote match = re.search("(\d+\.\d+\.\d+\.\d+)", remote) ip = match.group(1) when = when if when != '-' else 0 ntp_stats.append({ "remote": py23_compat.text_type(ip), "referenceid": py23_compat.text_type(refid), "synchronized": bool(synchronized), "stratum": int(st), "type": py23_compat.text_type(t), "when": py23_compat.text_type(when), "hostpoll": int(hostpoll), "reachability": int(reachability), "delay": float(delay), "offset": float(offset), "jitter": float(jitter) }) return ntp_stats def get_ntp_peers(self): output = self.device.send_command("ntpq -np") output_peers = output.split("\n")[2:] ntp_peers = dict() for line in output_peers: if len(line) > 0: match = re.search("(\d+\.\d+\.\d+\.\d+)\s+", line) ntp_peers.update({py23_compat.text_type(match.group(1)): {}}) return ntp_peers def get_bgp_neighbors(self): # 'description', 'sent_prefixes' and 'received_prefixes' are not implemented yet """ 'show ip bgp summary' output example: BGP router identifier 192.168.1.2, local AS number 64520 IPv4 Unicast - max multipaths: ebgp 1 ibgp 1 RIB entries 3, using 288 bytes of memory Peers 3, using 13 KiB of memory Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd 192.168.1.1 4 64519 7226 7189 0 0 0 4d23h40m 1 192.168.1.3 4 64521 7132 7103 0 0 0 4d21h05m 0 192.168.1.4 4 64522 0 0 0 0 0 never Active """ output = self.device.send_command("show ip bgp summary") output = output.split("\n") match = re.search( ".* router identifier (\d+\.\d+\.\d+\.\d+), local AS number (\d+)", output[0]) if not match: return {} router_id = py23_compat.text_type(match.group(1)) local_as = int(match.group(2)) bgp_neighbor_data = dict() bgp_neighbor_data["global"] = dict() bgp_neighbor_data["global"]["router_id"] = router_id bgp_neighbor_data["global"]["peers"] = {} # delete the header and empty element bgp_info = [i.strip() for i in output[6:-2] if i is not ""] for i in bgp_info: if len(i) > 0: peer_id, bgp_version, remote_as, msg_rcvd, msg_sent, table_version, \ in_queue, out_queue, up_time, state_prefix = i.split() is_enabled = "(Admin)" not in state_prefix received_prefixes = None try: state_prefix = int(state_prefix) received_prefixes = int(state_prefix) is_up = True except ValueError: state_prefix = -1 received_prefixes = -1 is_up = False if bgp_version == "4": address_family = "ipv4" elif bgp_version == "6": address_family = "ipv6" else: raise ValueError("BGP neighbor parsing failed") """ 'show ip bgp neighbors 192.168.1.1' output example: BGP neighbor is 192.168.1.1, remote AS 64519, local AS 64520, external link BGP version 4, remote router ID 192.168.1.1 For address family: IPv4 Unicast ~~~ Community attribute sent to this neighbor(both) 1 accepted prefixes ~~~ """ bgp_detail = self.device.send_command( "show ip bgp neighbors %s" % peer_id) match_rid = re.search( "remote router ID (\d+\.\d+\.\d+\.\d+).*", bgp_detail) remote_rid = match_rid.group(1) match_prefix_accepted = re.search("(\d+) accepted prefixes", bgp_detail) accepted_prefixes = match_prefix_accepted.group(1) bgp_neighbor_data["global"]["peers"].setdefault(peer_id, {}) peer_dict = { "description": py23_compat.text_type(""), "is_enabled": bool(is_enabled), "local_as": int(local_as), "is_up": bool(is_up), "remote_id": py23_compat.text_type(remote_rid), "uptime": int(self._bgp_time_conversion(up_time)), "remote_as": int(remote_as) } af_dict = dict() af_dict[address_family] = { "sent_prefixes": int(-1), "accepted_prefixes": int(accepted_prefixes), "received_prefixes": int(received_prefixes) } peer_dict["address_family"] = af_dict bgp_neighbor_data["global"]["peers"][peer_id] = peer_dict return bgp_neighbor_data def _bgp_time_conversion(self, bgp_uptime): # uptime_letters = set(["y", "w", "h", "d"]) if "never" in bgp_uptime: return -1 else: if "y" in bgp_uptime: match = re.search("(\d+)(\w)(\d+)(\w)(\d+)(\w)", bgp_uptime) uptime = ((int(match.group(1)) * self._YEAR_SECONDS) + (int(match.group(3)) * self._WEEK_SECONDS) + (int(match.group(5)) * self._DAY_SECONDS)) return uptime elif "w" in bgp_uptime: match = re.search("(\d+)(\w)(\d+)(\w)(\d+)(\w)", bgp_uptime) uptime = ((int(match.group(1)) * self._WEEK_SECONDS) + (int(match.group(3)) * self._DAY_SECONDS) + (int(match.group(5)) * self._HOUR_SECONDS)) return uptime elif "d" in bgp_uptime: match = re.search("(\d+)(\w)(\d+)(\w)(\d+)(\w)", bgp_uptime) uptime = ((int(match.group(1)) * self._DAY_SECONDS) + (int(match.group(3)) * self._HOUR_SECONDS) + (int(match.group(5)) * self._MINUTE_SECONDS)) return uptime else: hours, minutes, seconds = map(int, bgp_uptime.split(":")) uptime = ((hours * self._HOUR_SECONDS) + (minutes * self._MINUTE_SECONDS) + seconds) return uptime def get_interfaces_counters(self): # 'rx_unicast_packet', 'rx_broadcast_packets', 'tx_unicast_packets', # 'tx_multicast_packets' and 'tx_broadcast_packets' are not implemented yet """ 'show interfaces detail' output example: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 00:50:56:86:8c:26 brd ff:ff:ff:ff:ff:ff ~~~ RX: bytes packets errors dropped overrun mcast 35960043 464584 0 221 0 407 TX: bytes packets errors dropped carrier collisions 32776498 279273 0 0 0 0 """ output = self.device.send_command("show interfaces detail") interfaces = re.findall("(\S+): <.*", output) # count = re.findall("(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+", output) count = re.findall("(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)", output) counters = dict() j = 0 for i in count: if j % 2 == 0: rx_errors = i[2] rx_discards = i[3] rx_octets = i[0] rx_unicast_packets = i[1] rx_multicast_packets = i[5] rx_broadcast_packets = -1 else: counters.update({ interfaces[j // 2]: { "tx_errors": int(i[2]), "tx_discards": int(i[3]), "tx_octets": int(i[0]), "tx_unicast_packets": int(i[1]), "tx_multicast_packets": int(-1), "tx_broadcast_packets": int(-1), "rx_errors": int(rx_errors), "rx_discards": int(rx_discards), "rx_octets": int(rx_octets), "rx_unicast_packets": int(rx_unicast_packets), "rx_multicast_packets": int(rx_multicast_packets), "rx_broadcast_packets": int(rx_broadcast_packets) } }) j += 1 return counters def get_snmp_information(self): # 'acl' is not implemented yet output = self.device.send_command("show configuration") # convert the configuration to dictionary config = vyattaconfparser.parse_conf(output) snmp = dict() snmp["community"] = dict() try: for i in config["service"]["snmp"]["community"]: snmp["community"].update({ i: { "acl": py23_compat.text_type(""), "mode": py23_compat.text_type( config["service"]["snmp"]["community"][i] ["authorization"]) } }) snmp.update({ "chassis_id": py23_compat.text_type(""), "contact": py23_compat.text_type(config["service"]["snmp"]["contact"]), "location": py23_compat.text_type(config["service"]["snmp"]["location"]) }) return snmp except KeyError: return {} def get_facts(self): output_uptime = self.device.send_command( "cat /proc/uptime | awk '{print $1}'") uptime = int(float(output_uptime)) output = self.device.send_command("show version").split("\n") ver_str = [line for line in output if "Version" in line][0] version = self.parse_version(ver_str) sn_str = [line for line in output if "S/N" in line][0] snumber = self.parse_snumber(sn_str) hwmodel_str = [line for line in output if "HW model" in line][0] hwmodel = self.parse_hwmodel(hwmodel_str) output = self.device.send_command("show configuration") config = vyattaconfparser.parse_conf(output) if "host-name" in config["system"]: hostname = config["system"]["host-name"] else: hostname = None if "domain-name" in config["system"]: fqdn = config["system"]["domain-name"] else: fqdn = "" iface_list = list() for iface_type in config["interfaces"]: for iface_name in config["interfaces"][iface_type]: iface_list.append(iface_name) facts = { "uptime": int(uptime), "vendor": py23_compat.text_type("VyOS"), "os_version": py23_compat.text_type(version), "serial_number": py23_compat.text_type(snumber), "model": py23_compat.text_type(hwmodel), "hostname": py23_compat.text_type(hostname), "fqdn": py23_compat.text_type(fqdn), "interface_list": iface_list } return facts @staticmethod def parse_version(ver_str): version = ver_str.split()[-1] return version @staticmethod def parse_snumber(sn_str): sn = sn_str.split(":") return sn[1].strip() @staticmethod def parse_hwmodel(model_str): model = model_str.split(":") return model[1].strip() def get_interfaces_ip(self): output = self.device.send_command("show interfaces") output = output.split("\n") # delete the header line and the interfaces which has no ip address if len(output[-1]) > 0: ifaces = [x for x in output[3:] if "-" not in x] else: ifaces = [x for x in output[3:-1] if "-" not in x] ifaces_ip = dict() for iface in ifaces: iface = iface.split() if len(iface) != 1: iface_name = iface[0] # Delete the "Interface" column iface = iface[1:-1] # Key initialization ifaces_ip[iface_name] = dict() ip_addr, mask = iface[0].split("/") ip_ver = self._get_ip_version(ip_addr) # Key initialization if ip_ver not in ifaces_ip[iface_name]: ifaces_ip[iface_name][ip_ver] = dict() ifaces_ip[iface_name][ip_ver][ip_addr] = { "prefix_length": int(mask) } return ifaces_ip @staticmethod def _get_ip_version(ip_address): if ":" in ip_address: return "ipv6" elif "." in ip_address: return "ipv4" def get_users(self): output = self.device.send_command("show configuration commands").split( "\n") user_conf = [x.split() for x in output if "login user" in x] # Collect all users' name user_name = list(set([x[4] for x in user_conf])) user_auth = dict() for user in user_name: sshkeys = list() # extract the configuration which relates to 'user' for line in [x for x in user_conf if user in x]: # "set system login user alice authentication encrypted-password 'abc'" if line[6] == "encrypted-password": password = line[7].strip("'") # set system login user alice level 'admin' elif line[5] == "level": if line[6].strip("'") == "admin": level = 15 else: level = 0 # "set system login user alice authentication public-keys # [email protected] key 'ABC'" elif len(line) == 10 and line[8] == "key": sshkeys.append(line[9].strip("'")) user_auth.update({ user: { "level": level, "password": password, "sshkeys": sshkeys } }) return user_auth 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): # does not support multiple destination yet deadline = timeout * count command = "ping %s " % destination command += "ttl %d " % ttl command += "deadline %d " % deadline command += "size %d " % size command += "count %d " % count if source != "": command += "interface %s " % source ping_result = dict() output_ping = self.device.send_command(command) if "Unknown host" in output_ping: err = "Unknown host" else: err = "" if err is not "": ping_result["error"] = err else: # 'packet_info' example: # ['5', 'packets', 'transmitted,' '5', 'received,' '0%', 'packet', # 'loss,', 'time', '3997ms'] packet_info = output_ping.split("\n") if len(packet_info[-1]) > 0: packet_info = packet_info[-2] else: packet_info = packet_info[-3] packet_info = [x.strip() for x in packet_info.split()] sent = int(packet_info[0]) received = int(packet_info[3]) lost = sent - received # 'rtt_info' example: # ["0.307/0.396/0.480/0.061"] rtt_info = output_ping.split("\n") if len(rtt_info[-1]) > 0: rtt_info = rtt_info[-1] else: rtt_info = rtt_info[-2] match = re.search("([\d\.]+)/([\d\.]+)/([\d\.]+)/([\d\.]+)", rtt_info) if match is not None: rtt_min = float(match.group(1)) rtt_avg = float(match.group(2)) rtt_max = float(match.group(3)) rtt_stddev = float(match.group(4)) else: rtt_min = None rtt_avg = None rtt_max = None rtt_stddev = None ping_result["success"] = dict() ping_result["success"] = { "probes_sent": sent, "packet_loss": lost, "rtt_min": rtt_min, "rtt_max": rtt_max, "rtt_avg": rtt_avg, "rtt_stddev": rtt_stddev, "results": [{ "ip_address": destination, "rtt": rtt_avg }] } return ping_result
class PANOSDriver(NetworkDriver): def __init__(self, hostname, username, password, timeout=60, optional_args=None): self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.loaded = False self.changed = False self.device = None self.ssh_device = None self.ssh_connection = False self.merge_config = False if optional_args is None: optional_args = {} netmiko_argument_map = { 'port': None, 'verbose': False, 'use_keys': False, 'key_file': None, 'ssh_strict': False, 'system_host_keys': False, 'alt_host_keys': False, 'alt_key_file': '', 'ssh_config_file': None, } fields = netmiko_version.split('.') fields = [int(x) for x in fields] maj_ver, min_ver, bug_fix = fields if maj_ver >= 2: netmiko_argument_map['allow_agent'] = False elif maj_ver == 1 and min_ver >= 1: netmiko_argument_map['allow_agent'] = False # Build dict of any optional Netmiko args self.netmiko_optional_args = {} for k, v in netmiko_argument_map.items(): try: self.netmiko_optional_args[k] = optional_args[k] except KeyError: pass self.api_key = optional_args.get('api_key', '') def open(self): try: if self.api_key: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_key=self.api_key) else: self.device = pan.xapi.PanXapi(hostname=self.hostname, api_username=self.username, api_password=self.password) except ConnectionException as e: raise ConnectionException(str(e)) def _open_ssh(self): try: self.ssh_device = ConnectHandler(device_type='paloalto_panos', ip=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) except ConnectionException as e: raise ConnectionException(str(e)) self.ssh_connection = True def close(self): self.device = None if self.ssh_connection: self.ssh_device.disconnect() self.ssh_connection = False self.ssh_device = None def _import_file(self, filename): if not self.api_key: key = self.device.keygen() else: key = self.api_key params = {'type': 'import', 'category': 'configuration', 'key': key} path = os.path.basename(filename) mef = requests_toolbelt.MultipartEncoder(fields={ 'file': (path, open(filename, 'rb'), 'application/octet-stream') }) requests.packages.urllib3.disable_warnings(InsecureRequestWarning) url = 'https://{0}/api/'.format(self.hostname) request = requests.post(url, verify=False, params=params, headers={'Content-Type': mef.content_type}, data=mef) # if something goes wrong just raise an exception request.raise_for_status() response = xml.etree.ElementTree.fromstring(request.content) if response.attrib['status'] == 'error': return False else: return path def is_alive(self): if self.device: if self.ssh_connection: is_alive = self.ssh_device.remote_conn.transport.is_active() else: is_alive = True else: is_alive = False return {'is_alive': is_alive} def load_replace_candidate(self, filename=None, config=None): if config: raise ReplaceConfigException("This method requires a config file.") elif filename: if self.loaded is False: if self._save_backup() is False: raise ReplaceConfigException( 'Error while storing backup config') path = self._import_file(filename) if path is False: msg = "Error while trying to move the config file to the device." raise ReplaceConfigException(msg) # Let's load the config. cmd = '<load><config><from>{0}</from></config></load>'.format(path) self.device.op(cmd=cmd) if self.device.status == 'success': self.loaded = True else: raise ReplaceConfigException( 'Error while loading config from {0}').format(path) else: raise ReplaceConfigException("This method requires a config file.") def _get_file_content(self, filename): try: with open(filename, 'r') as f: content = f.read() except IOError: raise MergeConfigException('Error while opening {0}. Make sure ' 'filename is correct.'.format(filename)) return content def _send_merge_commands(self, config, file_config): """ Netmiko is being used to push set commands. """ if self.loaded is False: if self._save_backup() is False: raise MergeConfigException('Error while storing backup ' 'config.') if self.ssh_connection is False: self._open_ssh() if file_config: if isinstance(config, str): config = config.splitlines() else: if isinstance(config, str): config = str(config).split() self.ssh_device.send_config_set(config) self.loaded = True self.merge_config = True def _get_candidate(self): candidate_command = '<show><config><candidate></candidate></config></show>' self.device.op(cmd=candidate_command) candidate = str(self.device.xml_root()) return candidate def _get_running(self): self.device.show() running = str(self.device.xml_root()) return running def get_config(self, retrieve='all'): configs = {} running = py23_compat.text_type('') candidate = py23_compat.text_type('') startup = py23_compat.text_type('') if retrieve == 'all': running = py23_compat.text_type(self._get_running()) candidate = py23_compat.text_type(self._get_candidate()) elif retrieve == 'running': running = py23_compat.text_type(self._get_running()) elif retrieve == 'candidate': candidate = py23_compat.text_type(self._get_candidate()) configs['running'] = running configs['candidate'] = candidate configs['startup'] = startup return configs def load_merge_candidate(self, filename=None, config=None): if filename: file_config = True content = self._get_file_content(filename) config = content.splitlines() self._send_merge_commands(config, file_config) elif config: file_config = False self._send_merge_commands(config, file_config) else: raise MergeConfigException('You must provide either a file ' 'or a set-format string') def compare_config(self): """ Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command. """ if self.ssh_connection is False: self._open_ssh() self.ssh_device.exit_config_mode() diff = self.ssh_device.send_command("show config diff") return diff.strip() def _save_backup(self): self.backup_file = 'config_{0}.xml'.format( str(datetime.now().date()).replace(' ', '_')) backup_command = '<save><config><to>{0}</to></config></save>'.format( self.backup_file) self.device.op(cmd=backup_command) if self.device.status == 'success': return True else: return False def commit_config(self): """ Netmiko is being used to commit the configuration because it takes a better care of results compared to pan-python. """ if self.loaded: if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() time.sleep(3) self.loaded = False self.changed = True except: # noqa if self.merge_config: raise MergeConfigException('Error while commiting config') else: raise ReplaceConfigException( 'Error while commiting config') else: raise ReplaceConfigException('No config loaded.') def discard_config(self): if self.loaded: discard_cmd = '<load><config><from>{0}</from></config></load>'.format( self.backup_file) self.device.op(cmd=discard_cmd) if self.device.status == 'success': self.loaded = False self.merge_config = False else: raise ReplaceConfigException( "Error while loading backup config.") def rollback(self): """ Netmiko is being used to commit the rollback configuration because it takes a better care of results compared to pan-python. """ if self.changed: rollback_cmd = '<load><config><from>{0}</from></config></load>'.format( self.backup_file) self.device.op(cmd=rollback_cmd) time.sleep(5) if self.ssh_connection is False: self._open_ssh() try: self.ssh_device.commit() self.loaded = False self.changed = False self.merge_config = False except: # noqa ReplaceConfigException("Error while loading backup config") def _extract_interface_list(self): self.device.op(cmd='<show><interface>all</interface></show>') interfaces_xml = xmltodict.parse(self.device.xml_root()) interfaces_json = json.dumps(interfaces_xml['response']['result']) interfaces = json.loads(interfaces_json) interface_set = set() for entry in interfaces.values(): for entry_contents in entry.values(): if isinstance(entry_contents, dict): # If only 1 interface is listed, xmltodict returns a dictionary, otherwise # it returns a list of dictionaries. entry_contents = [entry_contents] for intf in entry_contents: interface_set.add(intf['name']) return list(interface_set) def get_facts(self): facts = {} try: self.device.op(cmd='<show><system><info></info></system></show>') system_info_xml = xmltodict.parse(self.device.xml_root()) system_info_json = json.dumps( system_info_xml['response']['result']['system']) system_info = json.loads(system_info_json) except AttributeError: system_info = {} if system_info: facts['hostname'] = system_info['hostname'] facts['vendor'] = py23_compat.text_type('Palo Alto Networks') facts['uptime'] = int( convert_uptime_string_seconds(system_info['uptime'])) facts['os_version'] = system_info['sw-version'] facts['serial_number'] = system_info['serial'] facts['model'] = system_info['model'] facts['fqdn'] = py23_compat.text_type('N/A') facts['interface_list'] = self._extract_interface_list() facts['interface_list'].sort() return facts def get_lldp_neighbors(self): """Return LLDP neighbors details.""" neighbors = {} cmd = '<show><lldp><neighbors>all</neighbors></lldp></show>' try: self.device.op(cmd=cmd) lldp_table_xml = xmltodict.parse(self.device.xml_root()) lldp_table_json = json.dumps( lldp_table_xml['response']['result']['entry']) lldp_table = json.loads(lldp_table_json) except AttributeError: lldp_table = [] for lldp_item in lldp_table: local_int = lldp_item['@name'] if local_int not in neighbors.keys(): neighbors[local_int] = [] try: lldp_neighs = lldp_item.get('neighbors').get('entry') except AttributeError: lldp_neighs = '' if isinstance(lldp_neighs, dict): lldp_neighs = [lldp_neighs] for neighbor in lldp_neighs: n = {} n['hostname'] = neighbor['system-name'] n['port'] = neighbor['port-id'] neighbors[local_int].append(n) return neighbors def get_route_to(self, destination='', protocol=''): """Return route details to a specific destination, learned from a certain protocol.""" # Note, it should be possible to query the FIB: # "<show><routing><fib></fib></routing></show>" # To add informations to this getter routes = {} if destination: destination = "<destination>{0}</destination>".format(destination) if protocol: protocol = "<type>{0}</type>".format(protocol) cmd = "<show><routing><route>{0}{1}</route></routing></show>".format( protocol, destination) try: self.device.op(cmd=cmd) routes_table_xml = xmltodict.parse(self.device.xml_root()) routes_table_json = json.dumps( routes_table_xml['response']['result']['entry']) routes_table = json.loads(routes_table_json) except (AttributeError, KeyError): routes_table = [] if isinstance(routes_table, dict): routes_table = [routes_table] for route in routes_table: d = { 'current_active': False, 'last_active': False, 'age': -1, 'next_hop': u'', 'protocol': u'', 'outgoing_interface': u'', 'preference': -1, 'inactive_reason': u'', 'routing_table': u'default', 'selected_next_hop': False, 'protocol_attributes': {} } destination = route['destination'] flags = route['flags'] if 'A' in flags: d['current_active'] = True else: d['current_active'] = False if 'C' in flags: d['protocol'] = "connect" if 'S' in flags: d['protocol'] = "static" if 'R' in flags: d['protocol'] = "rip" if 'R' in flags: d['protocol'] = "rip" if 'O' in flags: d['protocol'] = "ospf" if 'B' in flags: d['protocol'] = "bgp" if 'H' in flags: d['protocol'] = "host" if route['age'] is not None: d['age'] = int(route['age']) if route['nexthop'] is not None: d['next_hop'] = route['nexthop'] if route['interface'] is not None: d['outgoing_interface'] = route['interface'] if route['metric'] is not None: d['preference'] = int(route['metric']) if route['virtual-router'] is not None: d['routing_table'] = route['virtual-router'] if destination not in routes.keys(): routes[destination] = [] routes[destination].append(d) return routes def get_interfaces(self): LOOPBACK_SUBIF_DEFAULTS = { 'is_up': True, 'is_enabled': True, 'speed': 0, 'last_flapped': -1.0, 'mac_address': '', 'description': 'N/A' } interface_dict = {} interface_list = self._extract_interface_list() for intf in interface_list: interface = {} cmd = "<show><interface>{0}</interface></show>".format(intf) try: self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps( interface_info_xml['response']['result']['hw']) interface_info = json.loads(interface_info_json) except KeyError as err: if 'loopback.' in intf and 'hw' in str(err): # loopback sub-ifs don't return a 'hw' key interface_dict[intf] = LOOPBACK_SUBIF_DEFAULTS continue raise interface['is_up'] = interface_info.get('state') == 'up' conf_state = interface_info.get('state_c') if conf_state == 'down': interface['is_enabled'] = False elif conf_state in ('up', 'auto'): interface['is_enabled'] = True else: msg = 'Unknown configured state {} for interface {}'.format( conf_state, intf) raise RuntimeError(msg) interface['last_flapped'] = -1.0 interface['speed'] = interface_info.get('speed') # Loopback and down interfaces if interface['speed'] in ('[n/a]', 'unknown'): interface['speed'] = 0 else: interface['speed'] = int(interface['speed']) interface['mac_address'] = standardize_mac( interface_info.get('mac')) interface['description'] = py23_compat.text_type('N/A') interface_dict[intf] = interface return interface_dict def get_interfaces_ip(self): '''Return IP interface data.''' def extract_ip_info(parsed_intf_dict): ''' IPv4: - Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'. - Secondary IP's are in '<addr>'. If no secondaries, this field is not returned by the xmltodict.parse() method. IPv6: - All addresses are returned in '<addr6>'. If no v6 configured, this is not returned either by xmltodict.parse(). Example of XML response for an intf with multiple IPv4 and IPv6 addresses: <response status="success"> <result> <ifnet> <entry> <name>ethernet1/5</name> <zone/> <fwd>N/A</fwd> <vsys>1</vsys> <dyn-addr/> <addr6> <member>fe80::d61d:71ff:fed8:fe14/64</member> <member>2001::1234/120</member> </addr6> <tag>0</tag> <ip>169.254.0.1/30</ip> <id>20</id> <addr> <member>1.1.1.1/28</member> </addr> </entry> {...} </ifnet> <hw> {...} </hw> </result> </response> ''' intf = parsed_intf_dict['name'] _ip_info = {intf: {}} v4_ip = parsed_intf_dict.get('ip') secondary_v4_ip = parsed_intf_dict.get('addr') v6_ip = parsed_intf_dict.get('addr6') if v4_ip != 'N/A': address, pref = v4_ip.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = { 'prefix_length': int(pref) } if secondary_v4_ip is not None: members = secondary_v4_ip['member'] if not isinstance(members, list): # If only 1 secondary IP is present, xmltodict converts field to a string, else # it converts it to a list of strings. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = { 'prefix_length': int(pref) } if v6_ip is not None: members = v6_ip['member'] if not isinstance(members, list): # Same "1 vs many -> string vs list of strings" comment. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv6', {})[address] = { 'prefix_length': int(pref) } # Reset dictionary if no addresses were found. if _ip_info == {intf: {}}: _ip_info = {} return _ip_info ip_interfaces = {} cmd = "<show><interface>all</interface></show>" self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps( interface_info_xml['response']['result']['ifnet']['entry']) interface_info = json.loads(interface_info_json) if isinstance(interface_info, dict): # Same "1 vs many -> dict vs list of dicts" comment. interface_info = [interface_info] for interface_dict in interface_info: ip_info = extract_ip_info(interface_dict) if ip_info: ip_interfaces.update(ip_info) return ip_interfaces
print "\n", Pynet1Prompt, "\n", Pynet2Prompt, "\n", JuniperPrompt, "\n" print "Entering configuration mode..." time.sleep(2) Pynet1Config = Pynet1Connect.config_mode() Pynet2Config = Pynet2Connect.config_mode() JuniperConfig = JuniperConnect.config_mode() print "\n", Pynet1Config, "\n", Pynet2Config, "\n", JuniperConfig, "\n" #Instead of printing out the config mode string, you can call the function "check_config_mode()" #Pynet1Connect.check_config_mode() print "Exiting configuration mode..." time.sleep(2) Pynet1ExitConfig = Pynet1Connect.exit_config_mode() Pynet2ExitConfig = Pynet2Connect.exit_config_mode() JuniperExitConfig = JuniperConnect.exit_config_mode() print "\n", Pynet1ExitConfig, "\n", Pynet2ExitConfig, "\n", JuniperExitConfig, "\n" print "Checking interfaces' IPs..." time.sleep(2) Pynet1IpInt = Pynet1Connect.send_command('show ip int brief') Pynet2IpInt = Pynet2Connect.send_command('show ip int brief') JuniperIpInt = JuniperConnect.send_command('show interfaces terse | match "up up"') print "\n", Pynet1IpInt, "\n\n", Pynet2IpInt, "\n\n", JuniperIpInt, "\n" print "Sending a few config commands to the Juniper..." time.sleep(2)
#!/usr/bin/env python from netmiko import ConnectHandler import netmiko password = '******' pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } py2 = ConnectHandler(**pynet2) py2.config_mode() py2.send_command("logging buffered 8888") py2.exit_config_mode()
class NetmikoSSH(object): """Contains methods for managing and using SSH connections for Network Devices using Netmiko""" __MAX_RECV_BUF = 10 * 1024 * 1024 __existing_connections = {} def __init__(self): self._session = None self._node = None self._device = {} @staticmethod def _node_hash(node, port): """Get IP address and port hash from node dictionary. :param node: Node in topology. :param port: :type node: dict :return: IP address and port for the specified node. :rtype: int """ return hash(frozenset([node['mgmt_ip'], port])) @staticmethod def _get_device_type(node): device_os = node['os'] if str(device_os) in os_netmiko_map.keys(): return os_netmiko_map[str(device_os)] return None def net_connect(self, node): """Connect to node using Netmiko's inbuilt libraries. :param node: The node to disconnect from. :type node: dict """ self._node = node ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: self._session = NetmikoSSH.__existing_connections[node_hash] logger.debug('reusing ssh: {0}'.format(self._session)) else: start = time() self._device = { 'device_type': NetmikoSSH._get_device_type(node), 'ip': node['mgmt_ip'], 'username': node['username'], 'password': node['password'], 'port': ssh_port } self._session = ConnectHandler(**self._device) NetmikoSSH.__existing_connections[node_hash] = self._session logger.trace('connect took {} seconds'.format(time() - start)) logger.debug('new connection: {0}'.format(self._session)) logger.debug('Connections: {0}'.format( str(NetmikoSSH.__existing_connections))) def net_disconnect(self, node): """Close SSH connection to the node. :param node: The node to disconnect from. :type node: dict """ ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: logger.debug('Disconnecting peer: {}, {}'.format( node['name'], ssh_port)) ssh = NetmikoSSH.__existing_connections.pop(node_hash) self._session.disconnect() def _reconnect(self): """Close the SSH connection and open it again.""" node = self._node self.net_disconnect(node) self.net_connect(node) def config_mode(self): """Enter into config mode """ self.net_connect(self._node) self._session.config_mode() def check_config_mode(self): """ Check if session is currently in config mode""" self.net_connect(self._node) return self._session.check_config_mode() def exit_config_mode(self): """Exit config mode""" self.net_connect(self._node) self._session.exit_config_mode() def clear_buffer(self): """ Clear logging buffer """ self.net_connect(self._node) self._session.clear_buffer() def enable(self): """ Enter Enable Mode""" self.net_connect(self._node) self._session.enable() def exit_enable_mode(self): """ Exit enable mode """ self.net_connect(self._node) self._session.exit_enable_mode() def find_prompt(self): """Return the current router prompt""" self.net_connect(self._node) self._session.find_prompt() def send_command(self, cmd): """Send command down the SSH channel and return output back :param cmd :type cmd: str """ if cmd is None: raise TypeError('Command parameter is None') if len(cmd) == 0: raise ValueError('Empty command parameter') self.net_connect(self._node) return self._session.send_command(cmd) def send_config_set(self, config_cmds): """Send a set of configuration commands to remote device :param config_cmds :type config_cmds: str """ if config_cmds is None: raise TypeError('Config Cmds parameter is None') self.net_connect(self._node) print "Netmiko NODE !!!\n\n" print self._node return self._session.send_config_set(config_cmds) def send_config_from_file(self, cfg_file): """Send a set of configuration commands loaded from a file :param cfg_file :type cfg_file: file """ if not os.path.isfile(cfg_file): raise TypeError('Config file does not exist') self.net_connect(self._node) self._session.send_config_from_file(cfg_file)
net_device = { "host": 'cisco4.lasthop.io', "username": '******', "password": '******', "secret": '88newclass', "device_type": 'cisco_ios', "session_log":'my_cmd_logs.txt' } start_time = datetime.now() device = ConnectHandler(**net_device) print(device.find_prompt()) output = device.config_mode() print(device.find_prompt()) output = device.exit_config_mode() print(device.find_prompt()) print(device.write_channel('disable\n')) time.sleep(2) print(device.read_channel()) print(device.find_prompt()) print(device.enable()) print(device.find_prompt()) #pprint(output) device.disconnect() finish = datetime.now() dur = finish - start_time duration = dur.total_seconds()
def run(self): if self.device['device_type'] == 'cisco_ios_serial': try: console = ConnectHandler( **self.device ) # Connect to the Device to verify credentials. config_mode = console.check_config_mode() if config_mode is True: console.exit_config_mode() self.signal.emit('Router was in config mode try again.') return console.enable() # Enter Enable Mode show_ver = console.send_command('show run | inc version 1') self.signal.emit(show_ver) version = self.get_version_cisco(show_ver) if version >= 15.4: pass else: show_flash = console.send_command('dir flash: | i .bin') self.signal.emit('----ERROR----\n' ' Old version of IOS Detected\n' ' Correct version may be in flash:') self.signal.emit(show_flash) self.signal.emit( '\n>========== Reminder ==========<\n' 'Ensure the config you plan to load is compatible\n' ' with the version of IOS you are using.\n ' 'If not contact the help desk.\n' '>========== Reminder ==========<\n') console.disconnect( ) # disconnect so it can be modified later on the LoadTab self.signal.emit( 'Credentials Verified on Console!') # Congrats you made it except ValueError: # most likely com port fault. self.signal.emit( '...COM Port does not appear to be working. \nTry one of these:' ) ports = list(serial.tools.list_ports.comports() ) # You used the wrong one here let me help you. for p in ports: # may just automate this in the future using this method if only one port is found self.signal.emit(p[0]) return except NetMikoAuthenticationException: # Exactly what it says in the error. self.signal.emit( "Check your username/password. Make sure you have an account on this device." ) return elif self.device['device_type'] == 'cisco_ios_telnet': try: telnet = ConnectHandler( **self.device ) # Connect to the Device to verify credentials. telnet.enable() # Enter Enable Mode if telnet == True: telnet.send_command('exit') show_ver = telnet.send_command('show run | inc version 1') self.signal.emit(show_ver) version = self.get_version_cisco(show_ver) if version >= 15.4: pass else: show_flash = telnet.send_command('dir flash: | i .bin') self.signal.emit('----ERROR----\n' ' Old version of IOS Detected\n' ' Correct version may be in flash:') self.signal.emit(show_flash) self.signal.emit( '\n>========== Reminder ==========<\n' 'Ensure the config you plan to load is compatible\n' ' with the version of IOS you are using.\n ' 'If not contact the help desk.\n' '>========== Reminder ==========<\n') telnet.disconnect() self.signal.emit('Credentials Verified on Telnet!') except TimeoutError: # Exactly what it says in the error. self.signal.emit( "Telnet Error: Make sure the IP address is correct.") return except NetMikoAuthenticationException: # Exactly what it says in the error. self.signal.emit( "Check your username/password. Make sure you have an account on this device." ) return elif self.device['device_type'] == 'cisco_ios': try: ssh = ConnectHandler( **self.device ) # Connect to the Device to verify credentials. ssh.enable() # Enter Enable Mode if ssh == True: ssh.send_command('exit') show_ver = ssh.send_command('show run | inc version 1') self.signal.emit(show_ver) version = self.get_version_cisco(show_ver) if version >= 15.4: pass else: show_flash = ssh.send_command('dir flash: | i .bin') self.signal.emit('----ERROR----\n' ' Old version of IOS Detected\n' ' Correct version may be in flash:') self.signal.emit(show_flash) self.signal.emit( '\n>========== Reminder ==========<\n' 'Ensure the config you plan to load is compatible\n' ' with the version of IOS you are using.\n ' 'If not contact the help desk.\n' '>========== Reminder ==========<\n') ssh.disconnect() self.signal.emit('Credentials Verified on SSH!') except NetMikoTimeoutException: # Exactly what it says in the error. self.signal.emit( "SSH Error: Make sure the IP address is correct.") return except NetMikoAuthenticationException: # Exactly what it says in the error. self.signal.emit( "Check your username/password. Make sure you have an account on this device." ) return else: return
#!/usr/bin/env python from __future__ import print_function from netmiko import ConnectHandler pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': '******', 'port': 22 } net_connect = ConnectHandler(**pynet2) net_connect.config_mode() if net_connect.check_config_mode() is True: print(net_connect.find_prompt()) net_connect.exit_config_mode() net_connect.disconnect()
from netmiko import ConnectHandler from getpass import getpass password = getpass() NB_3850_8 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } nick_3850 = ConnectHandler(**NB_3850_8) nick_3850.find_prompt() nick_3850.exit_config_mode() nick_3850.config_mode() output = nick_3850.check_config_mode() print 'In configuration mode:', output
print rtr1_conn.find_prompt() print rtr2_conn.find_prompt() print juniper_srx_conn.find_prompt() rtr2_conn.config_mode() print "On rtr1 are we in config mode?" print rtr1_conn.check_config_mode() print "On rtr2 are we in config mode?" print rtr2_conn.check_config_mode() print "On juniper_srx are we in config mode?" print juniper_srx_conn.check_config_mode() rtr2_conn.exit_config_mode() show_commands = ['show arp'] output = rtr1_conn.send_command(show_commands[0]) print output output = rtr2_conn.send_command(show_commands[0]) print output output = juniper_srx_conn.send_command(show_commands[0]) print output
from netmiko import ConnectHandler from getpass import getpass password = getpass() NB_3850_8 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username' : 'pyclass', 'password': password, 'port' : 8022, } nick_3850 = ConnectHandler(**NB_3850_8) nick_3850.find_prompt() nick_3850.exit_config_mode() nick_3850.config_mode() output = nick_3850.check_config_mode() print 'In configuration mode:' , output
pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } # Connect to Cisco Router 2 pynet_rtr2 = ConnectHandler(**pynet2) # Enter Config mode pynet_rtr2.config_mode() if (pynet_rtr2.check_config_mode()): outp = pynet_rtr2.send_command('logging buffered 25000') # Exit Config mode pynet_rtr2.exit_config_mode() # Obtain the running Config outp = pynet_rtr2.send_command('show runn | inc logging buffered 25000') if re.search(r'logging buffered 25000', outp): print "Config changed successfully!" else: print "Config changed unsuccessfully!" else: print "Failed to enter Config mode!"
config_lines = [ "logging buffered 20000 critical", "no logging console", "bad command", "ntp server 130.126.24.24", "ntp server 152.2.21.1", ] ssh_conn = ConnectHandler(**device) try: output = ssh_conn.send_config_set(config_lines, error_pattern=r"% Invalid input") except ConfigInvalidException: # send_config_set failed so will still be in configuration mode ssh_conn.exit_config_mode() print("\nAn exception occurred configuring the device...") print("Recover configuration!") print("-" * 40) recover = "bootflash:/base_config.txt" cmd = f"configure replace {recover} force revert trigger error" recover_out = ssh_conn.send_command( cmd, expect_string=r"#", strip_prompt=False, strip_command=False ) print("Output from recovery command:") print(recover_out) print("-" * 40) print() finally:
def main(): try: hostname = raw_input("Enter remote host to test: ") username = raw_input("Enter remote username: "******"Enter remote host to test: ") username = input("Enter remote username: "******"***** Testing enable mode *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_enable_mode() print("Out of enable mode") print(net_connect.find_prompt()) # Test config mode print() print("***** Testing config mode *****") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: in config mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_config_mode() print("Out of config mode") print(net_connect.find_prompt()) # Test config mode (when already at root prompt) print() print("***** Testing config mode when already root *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) print("Test config_mode while already at root prompt") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: still at root prompt") else: print("Fail...") net_connect.exit_config_mode() # Should do nothing net_connect.exit_enable_mode() print("Out of config/enable mode") print(net_connect.find_prompt()) # Send config commands print() print("***** Testing send_config_set *****") print(net_connect.find_prompt()) output = net_connect.send_config_set(['ls -al']) print(output) print()
class IOSDevice(BaseDevice): def __init__(self, host, username, password, secret='', port=22, **kwargs): super(IOSDevice, self).__init__(host, username, password, vendor='cisco', device_type=IOS_SSH_DEVICE_TYPE) self.native = None self.host = host self.username = username self.password = password self.secret = secret self.port = int(port) self._connected = False self.open() def open(self): if self._connected: try: self.native.find_prompt() except: self._connected = False if not self._connected: self.native = ConnectHandler(device_type='cisco_ios', ip=self.host, username=self.username, password=self.password, port=self.port, secret=self.secret, verbose=False) self._connected = True def close(self): if self._connected: self.native.disconnect() self._connected = False def _enter_config(self): self._enable() self.native.config_mode() def _enable(self): self.native.exit_config_mode() if not self.native.check_enable_mode(): self.native.enable() 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(command) if '% ' in response or 'Error:' in response: raise CommandError(command, response) return response 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 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 def save(self, filename='startup-config'): command = 'copy running-config %s' % filename expect_string = '\[%s\]' % filename self.show(command, expect=True, expect_string=expect_string) time.sleep(5) self.show('\n') return True 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 file_copy_remote_exists(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() if fc.check_file_exists() and fc.compare_md5(): return True return False def file_copy(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() # 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: raise FileTransferError finally: fc.close_scp_chan() def reboot(self, timer=0, confirm=False): if confirm: def handler(signum, frame): raise RebootSignal('Interupting 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('no') self.native.send_command('\n') except RebootSignal: signal.alarm(0) signal.alarm(0) else: print('Need to confirm reboot with confirm=True') def _is_catalyst(self): return self.facts['model'].startswith('WS-') def set_boot_options(self, image_name, **vendor_specifics): if self._is_catalyst(): self.config('boot system flash:/%s' % image_name) else: self.config_list(['no boot system', 'boot system flash %s' % image_name]) def get_boot_options(self): if self._is_catalyst(): show_boot_out = self.show('show boot') boot_path_regex = r'BOOT path-list\s+:\s+(\S+)' boot_path = re.search(boot_path_regex, show_boot_out).group(1) boot_image = boot_path.replace('flash:/', '') return dict(sys=boot_image) else: show_boot_out = self.show('show run | inc boot') boot_path_regex = r'boot system flash (\S+)' match = re.search(boot_path_regex, show_boot_out) if match: boot_image = match.group(1) else: boot_image = None return dict(sys=boot_image) def backup_running_config(self, filename): with open(filename, 'w') as f: f.write(self.running_config) 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_string(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) return '%02d:%02d:%02d:00' % (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 _interfaces_detailed_list(self): ip_int_br_out = self.show('show ip int br') ip_int_br_data = get_structured_data('cisco_ios_show_ip_int_brief.template', ip_int_br_out) return ip_int_br_data 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 _raw_version_data(self): show_version_out = self.show('show version') try: version_data = get_structured_data('cisco_ios_show_version.template', show_version_out)[0] return version_data except IndexError: return {} def rollback(self, rollback_to): try: self.show('configure replace flash:%s force' % rollback_to) except CommandError: raise RollbackError('Rollback unsuccessful. %s may not exist.' % rollback_to) def checkpoint(self, checkpoint_file): self.save(filename=checkpoint_file) @property def facts(self): if hasattr(self, '_facts'): return self._facts facts = {} facts['vendor'] = self.vendor version_data = self._raw_version_data() show_version_facts = convert_dict_by_key(version_data, ios_key_maps.BASIC_FACTS_KM) facts.update(show_version_facts) uptime_full_string = version_data['uptime'] facts['uptime'] = self._uptime_to_seconds(uptime_full_string) facts['uptime_string'] = self._uptime_to_string(uptime_full_string) facts['fqdn'] = 'N/A' facts['interfaces'] = list(x['intf'] for x in self._interfaces_detailed_list()) if show_version_facts['model'].startswith('WS'): facts['vlans'] = list(str(x['vlan_id']) for x in self._show_vlan()) else: facts['vlans'] = [] # ios-specific facts ios_facts = facts[IOS_SSH_DEVICE_TYPE] = {} ios_facts['config_register'] = version_data['config_register'] self._facts = facts return facts @property def running_config(self): return self.show('show running-config', expect=True) @property def startup_config(self): return self.show('show startup-config')
def ConfigurationTest(ip, Device_Type_Num=0, User_Pass_Num=0, Passowrd_Enable_Num=0): global num_New # so we can edit it in this Function # def ConfigurationTest(ip,Device_Type_Num= 0,User_Pass_Num= 0): if ConfigurationTest_Boolen == 1: return ConfigurationTest_Boolen == 1 # If increment of Num is out of range for User_Pass_Num and Device_Type_Num return 1 elif User_Pass_Num >= len(Username_Device): print(f"Username Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Device_Type_Num >= len(Device_Type): print(f"Connection type Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Passowrd_Enable_Num >= len(Passowrd_Device_Enable): print(f"Enable Pass Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 # If increment of Num is in range for User_Pass_Num and Device_Type_Num contune else: iosv_l2 = { 'device_type': str(Device_Type[Device_Type_Num] ), ##### Type of connection SSH/Telnet 'ip': str(ip), 'username': Username_Device[User_Pass_Num], 'password': Passowrd_Device[User_Pass_Num], 'global_delay_factor': 15, # if there is authentication problem allow this # 'secret':'cs' 'secret': Passowrd_Device_Enable[Passowrd_Enable_Num], # 'timeout':10 'session_timeout': 10 # if there is authentication problem allow this } try: # time.sleep(3) Conf_Variables = [ ] # To check if any faliure on the configuration after sending it net_connect = ConnectHandler(**iosv_l2) # print(net_connect.find_prompt()) ############ function to check output to send any confirmation message as pass or confirmation of yes or no def SpecialConfirmation(command, message, reply): net_connect.config_mode() #To enter config mode print("SpecialConfirmation Config") try: if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First Write Telnet") net_connect.remote_conn.write(str(command) + '\n') else: net_connect.remote_conn.sendall(str(command) + '\n') except: print("Exception For Sendall ") print("SpecialConfirmation Before Sleep") time.sleep(3) print("SpecialConfirmation after Sleep") if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First READ Telnet") output = net_connect.remote_conn.read_very_eager().decode( "utf-8", "ignore") else: output = net_connect.remote_conn.recv(65535).decode( 'utf-8') ReplyAppend = '' print("SpecialConfirmation output") print(output) try: if str(message) in output: for i in range(0, (len(reply))): ReplyAppend += str(reply[i]) + '\n' if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("SECOND Telnet") net_connect.remote_conn.write(ReplyAppend) output = net_connect.remote_conn.read_very_eager( ).decode("utf-8", "ignore") else: net_connect.remote_conn.sendall(ReplyAppend) output = net_connect.remote_conn.recv( 65535).decode('utf-8') print(output) except: print("Confirmation Exception Error") return output print("Entered Device Successfully \t" + ip + "\n") ###################################################################### ################ Here Is The Cisco Configuration #################### ###################################################################### print("check enable mode for " + str(ip)) if not net_connect.check_enable_mode(): net_connect.enable() print("entered enable mode for " + str(ip)) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After exiting config to perform show commands " + str(ip)) print("After checking config to perform show commands " + str(ip)) ###################################################################### print("Terminal length \n") ## Try this First Configuration_Output = "" Configuration_Output = net_connect.send_command_timing( "termin len 0" + '\n\n') # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n' ,strip_prompt=False,strip_command=False) ################### for ARP ############################################################### ###################################################################### # Configuration_Output_ID2=net_connect.send_command_timing("show ip arp vrf ID2 "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output_ID254=net_connect.send_command_timing("show ip arp vrf ID254 "+'\n\n' ,strip_prompt=False,strip_command=False) ###################################################################### # Configuration_Output=net_connect.send_command_timing("termin len 0"+'\n\n',delay_factor=5) # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) ########################################################################################################### ############################ Use TEXTFSM Template to get Show version ############################ ########################################################################################################### try: # Show_Version_TEXTFSM_List=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False, use_textfsm=True, textfsm_template="/home/khayat/Textfsm_Templates/cisco_ios_show_version.textfsm") # Test_Expect=net_connect.send_command("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False) # print ("\t\tTest_Expect") # print (Test_Expect) Show_Version_TEXTFSM_List = net_connect.send_command_timing( "show version " + '\n\n', strip_prompt=False, strip_command=False, use_textfsm=True) Show_Version_TEXTFSM_Dict = Show_Version_TEXTFSM_List[ 0] # this is because the output is in list then in Dict # print (type(Show_Version_TEXTFSM_List)) # print ((Show_Version_TEXTFSM_List)) # print (type(Show_Version_TEXTFSM_Dict)) # print ((Show_Version_TEXTFSM_Dict)) # print ("\n\n\n") # print ("\t\tConfiguration_Output_TEXTFSM") # for k,v in Show_Version_TEXTFSM_Dict.items() : # print (f"{k} :: {v}") if Show_Version_TEXTFSM_Dict["hardware"]: Hardware_IP = "\t\t" + str( Show_Version_TEXTFSM_Dict["hardware"] [0]) + f" {ip}___" + str( Show_Version_TEXTFSM_Dict["hostname"]) All_Hardware_Module_List.append(Hardware_IP) else: Hardware_IP_Empty_List.append(ip + " Hardware Empty") Hostname_Output = ip + ".__" + str( Show_Version_TEXTFSM_Dict["hostname"]) Worked_IPs_Old.append(ip) except Exception as e: print('Exception in show version\t' + ip) FailedIps.append(ip + " Exception in show version") IPs_ForIteration.append(ip) ########################################################################################################### # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n') # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',strip_prompt=False,strip_command=False) print(f"This is after getting SHOW for IP\t{ip}") # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n',delay_factor=5) ########################################################################################################### ################## Get each interfaces status using Script ################################################## ########################################################################################################### # List_Of_Inter=net_connect.send_command_timing("show interface status "+'\n\n') # # print ("\t\tList_Of_Inter") # List_of_Lines= Get_All_Inter(List_Of_Inter) # print ("\t\tList_of_Lines\n") # print (List_of_Lines) # print ("\t\tGet_Ports_Status") # Returned_List=Get_Ports_Status(List_of_Lines) # for i in Returned_List : # print (f"key\t{i}\tValue\t{Returned_List.get(i)} ") # ########################################################################################################### # ################## Get each interfaces IP using Script ################################################## # ########################################################################################################### # IPs_All_Interfaces=net_connect.send_command_timing("show ip interface br "+'\n\n') # Inter_IPs= Get_Interfaces_IP(IPs_All_Interfaces) # for x in Inter_IPs : # if x[-1] =="up" and x[-2]=="up" : # print (x) # print (x[1]) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if not net_connect.check_config_mode(): net_connect.config_mode() print("After entering config " + str(ip)) print("After checking config to perform configuration commands " + str(ip)) ###################################################################### ################ Set list of configuration ########################### ###################################################################### # List_cmd=[f"inte {Returned_List["disabled"][0]}","no shutd","ip add 192.168.100.100 255.255.255.0"] # print ("Returned_List[disabled][0]") # print (Returned_List.get("disabled")[0]) # Temp=str(Returned_List.get("disabled")[0]) # List_cmd=[f"inte {Temp}","no shutd"] # Output_Setting_Inter=net_connect.send_config_set(config_commands=List_cmd) # print ("Output_Setting_Inter") # print (Output_Setting_Inter) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After exiting config " + str(ip)) print("After checking config for CDP command\t" + str(ip)) ########################################################################################################### ################## Add new IPs from CDP Command ################################################## ########################################################################################################### ############################################################################### ######################## Using Script for cdp neighbors to get New IPs ############################################################################### # CDP_ALL=net_connect.send_command_timing("show cdp neighbors detail | i IP address: "+'\n\n') # print ("\t\tGet_CDP_Neighbors") # num_New = list(num_New) + list(Get_CDP_Neighbors (CDP_ALL , num)) ############################################################################### ######################## Using TextFSM for cdp neighbors ############################################################################### try: Show_CDP_Details_TEXTFSM_List = net_connect.send_command_timing( "show cdp neighbors detail " + '\n\n', strip_prompt=False, strip_command=False, use_textfsm=True) for n in Show_CDP_Details_TEXTFSM_List: Show_CDP_Details_TEXTFSM_Dict = n # this is because the output is in list then in Dict # print (type(Show_CDP_Details_TEXTFSM_List)) # print (Show_CDP_Details_TEXTFSM_List) # print (type(Show_CDP_Details_TEXTFSM_Dict)) # print (Show_CDP_Details_TEXTFSM_Dict) # print (type(Show_CDP_Details_TEXTFSM_Dict["management_ip"])) # print (Show_CDP_Details_TEXTFSM_Dict["management_ip"]) if "172." in Show_CDP_Details_TEXTFSM_Dict[ "management_ip"]: if Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in num and Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in num_New and Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in Worked_IPs_Old: num_New.append( Show_CDP_Details_TEXTFSM_Dict["management_ip"]) except Exception as e: print('Exception in show cdp neighbors \t' + ip) FailedIps.append(ip + " Exception in show cdp neighbors ") IPs_ForIteration.append(ip) ########################################################################################################### ################ Example on confirmation message Function ########################################################################################################### # if ip =="192.168.233.13": # print (str (SpecialConfirmation("crypto key generate rsa general-keys" ,"modulus" ,"1024"))) ########################################################################################################### ########################################################################################################### if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After last check config " + str(ip)) ################################################################################ ####################### Test Ping For Rang Of IP ############################## ################################################################################ # Active_ping_ip=[] # InActive_ping_ip=[] # Sub_Ip_ping="2.0.32." # for x in range(1,255) : # print (x) # Ip_ping=Sub_Ip_ping+str(x) # ping_result=net_connect.send_command_timing("ping "+Ip_ping+'\n\n' ,strip_prompt=False,strip_command=False) # # print (ping_result) # # ping_is_successful(ping_result) # # print (ping_is_successful(ping_result)) # # print (type(ping_is_successful(ping_result))) # if ping_is_successful(ping_result) : # Active_ping_ip.append(Ip_ping) # else : # InActive_ping_ip.append(Ip_ping) # print ("Active_ping_ip") # for x in Active_ping_ip : # print (x) # print ("\n\n\nInActive_ping_ip") # for x in InActive_ping_ip : # print (x) ############### Append Configuration Variables to Global Variable ########## # Conf_Variables.append(Hostname_Output) # print (Configuration_Output) # Conf_Variables.append(Configuration_Output) ############### Search in Configuration if any command error and return its IP ################ for y in Conf_Variables: if "% Invalid input detected at '^' marker." in y: FailedIps.append(ip + " Invalid input") ######################################################################################################### Hostname_Output_list.append(Hostname_Output) test = Configuration_Switch test += Configuration_Output test += Configuration_Router Configuration_Output_list.append(test) Configuration_Output_ID2_list.append(Configuration_Output_ID2) Configuration_Output_ID254_list.append(Configuration_Output_ID254) ############### SAVE Output IN FILES ####################### Global_Output.append(Hostname_Output) print("Exiting " + str(ip)) net_connect.disconnect() print("After Exiting " + str(ip)) ################### Exception ################################### except (NetMikoAuthenticationException ) as netmikoAuthenticationException: # print ('Authentication Failure\t' + ip) print( str(User_Pass_Num) + " " + str(Username_Device[User_Pass_Num]) + " failed Authentication\t" + ip) ################ Print error from msg from the main Lib print( f"netmikoAuthenticationException : {netmikoAuthenticationException}\n" ) User_Pass_Num += 1 # If it tried all users and pass and failed add it to failedIps if User_Pass_Num >= len(Username_Device): FailedIps.append(ip + " Authentication Error ") IPs_ForIteration.append(ip) # if User_Pass_Num < len(Username_Device) : # print("this is Authentication "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) # Recursive function return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (ValueError): print(str(Passowrd_Enable_Num) + "\tEnable Authentication\t" + ip) Passowrd_Enable_Num += 1 if Passowrd_Enable_Num >= len(Passowrd_Device_Enable): FailedIps.append(ip + " Enable Authentication Error ") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except socket_error as socket_err: ################ Print error from msg from the main Lib print( f"Socket Error: \n{socket_err}\t for IP {ip} trying another type of Connection\n" ) print("Continue") if '111' in f"Type {socket_err}": Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Socket or connection type Error") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) if '113' in f"Type {socket_err}": FailedIps.append(ip + " No route to the host") IPs_ForIteration.append(ip) return ConfigurationTest_Boolen == 1 FailedIps.append(ip + " Socket or connection type Error") IPs_ForIteration.append(ip) return ConfigurationTest_Boolen == 1 except (NetMikoTimeoutException) as netmikoTimeoutException: # print ('Timeout Failure\t' + ip) print(str(Device_Type_Num) + "\tTimeoutException\t" + ip) ################ Print error from msg from the main Lib print(f"netmikoTimeoutException : \n{netmikoTimeoutException}\n") Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Timeout Error") IPs_ForIteration.append(ip) # if Device_Type_Num < len(Device_Type) : # print("this is Timeout "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) # except (paramiko.ssh_exception.SSHException) as sshException : except (SSHException) as sshException: # print ('SSH Failure\t' + ip) print(str(Device_Type_Num) + "\tSSHException\t" + ip + "\n") ################ Print error from msg from the main Lib print( f"Unable to establish SSH connection: \n{sshException}\t for IP {ip}\n" ) Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " SSHException Error ") IPs_ForIteration.append(ip) # if Device_Type_Num < len(Device_Type) : # print("this is SSHException "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (ValueError): print( str(Passowrd_Enable_Num) + " " + str(Passowrd_Device_Enable[Passowrd_Enable_Num]) + " Failed Enable Authentication\t" + ip) Passowrd_Enable_Num += 1 if Passowrd_Enable_Num >= len(Passowrd_Device_Enable): FailedIps.append(ip + " Enable Authentication Error ") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (EOFError) as eof_Error: ################ Print error from msg from the main Lib print(f"eof_Error : \n{eof_Error}\n") # print ('End of File wihle attempting device\t' +ip) FailedIps.append(ip + " EOFError") IPs_ForIteration.append(ip) # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest_Boolen == 1 ################################################################### ######### if you want to show error , comment next lines if you want to show which Ips have error remove comment ############## ################################################################### # except Exception as e: # # print ('End of File wihle attempting device\t' +ip) # FailedIps.append(ip+" Exception as e") # # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) # return ConfigurationTest_Boolen==1 #################################################################### return ConfigurationTest_Boolen == 1
if __name__ == "__main__": verbose = True username = raw_input("Username: "******"Password: "******"crtlist") devlist = [d.rstrip() for d in f.readlines()] f.close() for dev in devlist: nc = ConnectHandler(device_type='juniper', ip=dev, username=username, password=password, verbose=verbose) # into config mode nc.config_mode() nc.send_command('delete forwarding-options apply-groups dhcp') nc.send_command('delete routing-instances apply-groups dhcp') print nc.send_command('show | compare') nc.send_command('rollback 0') #print "committing..." #nc.commit() nc.exit_config_mode() print "exiting" nc.disconnect()
class IOSDevice(BaseDevice): def __init__(self, host, username, password, secret='', port=22, **kwargs): super(IOSDevice, self).__init__(host, username, password, vendor='cisco', device_type=IOS_SSH_DEVICE_TYPE) self.native = None self.host = host self.username = username self.password = password self.secret = secret self.port = int(port) self._connected = False self.open() def open(self): if self._connected: try: self.native.find_prompt() except: self._connected = False if not self._connected: self.native = ConnectHandler(device_type='cisco_ios', ip=self.host, username=self.username, password=self.password, port=self.port, secret=self.secret, verbose=False) self._connected = True def close(self): if self._connected: self.native.disconnect() self._connected = False def _enter_config(self): self._enable() self.native.config_mode() def _enable(self): self.native.exit_config_mode() if not self.native.check_enable_mode(): self.native.enable() 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 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 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 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 - Incease 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 _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 file_copy_remote_exists(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() if fc.check_file_exists() and fc.compare_md5(): return True return False def file_copy(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() # 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: raise FileTransferError finally: fc.close_scp_chan() 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 _is_catalyst(self): return self.facts['model'].startswith('WS-') def set_boot_options(self, image_name, **vendor_specifics): if self._is_catalyst(): self.config('boot system flash:/%s' % image_name) else: self.config_list(['no boot system', 'boot system flash %s' % image_name]) def get_boot_options(self): if self._is_catalyst(): show_boot_out = self.show('show boot') boot_path_regex = r'BOOT path-list\s+:\s+(\S+)' boot_path = re.search(boot_path_regex, show_boot_out).group(1) boot_image = boot_path.replace('flash:/', '') return dict(sys=boot_image) else: show_boot_out = self.show('show run | inc boot') boot_path_regex = r'boot system flash (\S+)' match = re.search(boot_path_regex, show_boot_out) if match: boot_image = match.group(1) else: boot_image = None return dict(sys=boot_image) def backup_running_config(self, filename): with open(filename, 'w') as f: f.write(self.running_config) 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_string(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) return '%02d:%02d:%02d:00' % (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 _interfaces_detailed_list(self): ip_int_br_out = self.show('show ip int br') ip_int_br_data = get_structured_data('cisco_ios_show_ip_int_brief.template', ip_int_br_out) return ip_int_br_data 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 _raw_version_data(self): show_version_out = self.show('show version') try: version_data = get_structured_data('cisco_ios_show_version.template', show_version_out)[0] return version_data except IndexError: return {} def rollback(self, rollback_to): try: self.show('configure replace flash:%s force' % rollback_to) except CommandError: raise RollbackError('Rollback unsuccessful. %s may not exist.' % rollback_to) def checkpoint(self, checkpoint_file): self.save(filename=checkpoint_file) @property def facts(self): if hasattr(self, '_facts'): return self._facts facts = {} facts['vendor'] = self.vendor version_data = self._raw_version_data() show_version_facts = convert_dict_by_key(version_data, ios_key_maps.BASIC_FACTS_KM) facts.update(show_version_facts) uptime_full_string = version_data['uptime'] facts['uptime'] = self._uptime_to_seconds(uptime_full_string) facts['uptime_string'] = self._uptime_to_string(uptime_full_string) facts['fqdn'] = 'N/A' facts['interfaces'] = list(x['intf'] for x in self._interfaces_detailed_list()) if show_version_facts['model'].startswith('WS'): facts['vlans'] = list(str(x['vlan_id']) for x in self._show_vlan()) else: facts['vlans'] = [] # ios-specific facts ios_facts = facts[IOS_SSH_DEVICE_TYPE] = {} ios_facts['config_register'] = version_data['config_register'] self._facts = facts return facts @property def running_config(self): return self.show('show running-config', expect=True) @property def startup_config(self): return self.show('show startup-config')
"device_type": "cisco_ios", "session_log": "my_session.txt" } net_connect = ConnectHandler(**device1) output = net_connect.find_prompt() print(output) output = net_connect.config_mode() print(output) output = net_connect.find_prompt() print(output) output = net_connect.exit_config_mode() print(output) output = net_connect.find_prompt() print(output) output = net_connect.write_channel('disable \n') print(output) time.sleep(2) output = net_connect.read_channel() print(output) output = net_connect.enable() print(output)
"username": "******", "password": password, "device_type": "cisco_ios", "secret": password, "session_log": "my_output.txt" } net_connect = ConnectHandler(**device) prompt = net_connect.find_prompt() print(prompt) prompt = net_connect.config_mode() print(prompt) prompt = net_connect.exit_config_mode() print(prompt) net_connect.write_channel("disable\n") time.sleep(2) prompt = net_connect.read_channel() print(prompt) prompt = net_connect.enable() print(prompt) ''' print() cmds = ["show version", "show lldp neighbors"]
import time cisco4 = { "host":" cisco4.lasthop.io", "username": "******", "password": "******", "secret": "88newclass", "device_type": "cisco_ios", "session_log": "week2_exercise6_log.txt", } cisco4_connect = ConnectHandler(**cisco4) print(cisco4_connect.find_prompt()) cisco4_connect.config_mode() print(cisco4_connect.find_prompt()) cisco4_connect.exit_config_mode() print(cisco4_connect.find_prompt()) print("\nExit privileged exec (disable), Current Prompt: ") cisco4_connect.write_channel("disable\n") time.sleep(2) output = cisco4_connect.read_channel() print(output) print("\nRe-enter enable mode, Current Prompt: ") cisco4_connect.enable() print(cisco4_connect.find_prompt()) cisco4_connect.disconnect() print()
def main(): try: hostname = raw_input("Enter remote host to test: ") username = raw_input("Enter remote username: "******"Enter remote host to test: ") username = input("Enter remote username: "******"username": username, "use_keys": True, "ip": hostname, "device_type": "ovs_linux", "key_file": "/home/{}/.ssh/test_rsa".format(username), "verbose": False, } net_connect = ConnectHandler(**linux_test) print() print(net_connect.find_prompt()) # Test enable mode print() print("***** Testing enable mode *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_enable_mode() print("Out of enable mode") print(net_connect.find_prompt()) # Test config mode print() print("***** Testing config mode *****") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: in config mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_config_mode() print("Out of config mode") print(net_connect.find_prompt()) # Test config mode (when already at root prompt) print() print("***** Testing config mode when already root *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) print("Test config_mode while already at root prompt") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: still at root prompt") else: print("Fail...") net_connect.exit_config_mode() # Should do nothing net_connect.exit_enable_mode() print("Out of config/enable mode") print(net_connect.find_prompt()) # Send config commands print() print("***** Testing send_config_set *****") print(net_connect.find_prompt()) output = net_connect.send_config_set(["ls -al"]) print(output) print()
def ConfigurationTest(ip, Device_Type_Num=0, User_Pass_Num=0, Passowrd_Enable_Num=0): # def ConfigurationTest(ip,Device_Type_Num= 0,User_Pass_Num= 0): if ConfigurationTest_Boolen == 1: return ConfigurationTest_Boolen == 1 # If increment of Num is out of range for User_Pass_Num and Device_Type_Num return 1 elif User_Pass_Num >= len(Username_Device): print(f"Username Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Device_Type_Num >= len(Device_Type): print(f"Connection type Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Passowrd_Enable_Num >= len(Passowrd_Device_Enable): print(f"Enable Pass Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 # If increment of Num is in range for User_Pass_Num and Device_Type_Num contune else: iosv_l2 = { 'device_type': str(Device_Type[Device_Type_Num] ), ##### Type of connection SSH/Telnet 'ip': str(ip), 'username': Username_Device[User_Pass_Num], 'password': Passowrd_Device[User_Pass_Num], # 'global_delay_factor': 10, # 'secret':'cs' 'secret': Passowrd_Device_Enable[Passowrd_Enable_Num], # 'timeout':5 # 'session_timeout':5 } try: # time.sleep(3) Conf_Variables = [ ] # To check if any faliure on the configuration after sending it net_connect = ConnectHandler(**iosv_l2) # print(net_connect.find_prompt()) ############ function to check output to send any confirmation message as pass or confirmation of yes or no def SpecialConfirmation(command, message, reply): net_connect.config_mode() #To enter config mode print("SpecialConfirmation Config") try: if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First Write Telnet") net_connect.remote_conn.write(str(command) + '\n') else: net_connect.remote_conn.sendall(str(command) + '\n') except: print("Exception For Sendall ") print("SpecialConfirmation Before Sleep") time.sleep(3) print("SpecialConfirmation after Sleep") if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First READ Telnet") output = net_connect.remote_conn.read_very_eager().decode( "utf-8", "ignore") else: output = net_connect.remote_conn.recv(65535).decode( 'utf-8') ReplyAppend = '' print("SpecialConfirmation output") print(output) try: if str(message) in output: for i in range(0, (len(reply))): ReplyAppend += str(reply[i]) + '\n' if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("SECOND Telnet") net_connect.remote_conn.write(ReplyAppend) output = net_connect.remote_conn.read_very_eager( ).decode("utf-8", "ignore") else: net_connect.remote_conn.sendall(ReplyAppend) output = net_connect.remote_conn.recv( 65535).decode('utf-8') print(output) except: print("Confirmation Exception Error") return output print("Entered Device Successfully \t" + ip + "\n") ###################################################################### ################ Here Is The Cisco Configuration #################### ###################################################################### print("check enable mode for " + str(ip)) if not net_connect.check_enable_mode(): net_connect.enable() print("entered enable mode for " + str(ip)) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After exiting config " + str(ip)) print("After checking config " + str(ip)) ###################################################################### print("Terminal length \n") Configuration_Output = net_connect.send_command_timing( "termin len 0" + '\n\n') Configuration_Output = net_connect.send_command_timing( "show run " + '\n\n', strip_prompt=False, strip_command=False) Configuration_Output += net_connect.send_command_timing( "show ip inte br " + '\n\n', strip_prompt=False, strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n' ,strip_prompt=False,strip_command=False) ################### for ARP ############################################################### ###################################################################### # Configuration_Output_ID2=net_connect.send_command_timing("show ip arp vrf ID2 "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output_ID254=net_connect.send_command_timing("show ip arp vrf ID254 "+'\n\n' ,strip_prompt=False,strip_command=False) ###################################################################### # Configuration_Output=net_connect.send_command_timing("termin len 0"+'\n\n',delay_factor=5) # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n') # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',strip_prompt=False,strip_command=False) print(f"This is after getting SHOW for IP\t{ip}") Hostname_Output = net_connect.send_command( "show run | i hostname" + '\n\n', delay_factor=5) ########################################################################################################### ################## Add new IPs from CDP Command ################################################## ########################################################################################################### CDP_ALL = net_connect.send_command_timing( "show cdp neighbors detail | i IP address: " + '\n\n') # print("CDP_ALL\n") # print(CDP_ALL) # print(type(CDP_ALL)) # change output to list of lines CDP_Lines_List = CDP_ALL.splitlines( ) # change output to list of lines CDP_IPs_List = [] # change list of line to list of IPs wihtout IP address sentence for i in CDP_Lines_List: j = i.lstrip("IP address: ") CDP_IPs_List.append(j) # print("CDP_IPs_List for "+str(ip)) # print(CDP_IPs_List) # check on each ip if it's in the mangement range or not and append it to new list if it's not exsit in the IPs list for i in CDP_IPs_List: if "192" in i: # check on the IP to add it to the list if i not in num: num_New.append(i) # num.append(i) # CDP_IPs_List.remove(i) ########################################################################################################### ########################################################################################################### # if ip =="192.168.233.13": # print (str (SpecialConfirmation("crypto key generate rsa general-keys" ,"modulus" ,"1024"))) if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After second check config " + str(ip)) # for k in TestPingIPs : # ping_result=net_connect.send_command_timing("ping "+k) # print (str(k)+" is "+str(ping_is_successful(ping_result))+" from "+str(ip)) ################################################################################ ####################### Test Ping For Rang Of IP ############################## ################################################################################ # for IpPing in TestPingIPs : # PingPool="ping "+IpPing # TestPingResult=net_connect.send_command_timing(PingPool+'\n\n') # if ping_is_successful(TestPingResult) : # TruePing.append(IpPing) # else : # FalsePing.append(IpPing) Spilt_Hostname_Ouput = Hostname_Output.split() Hostname_Output = ip + ".__" + Spilt_Hostname_Ouput[-1] # print ("After Split") ############### Append Configuration Variables to Global Variable ########## Conf_Variables.append(Hostname_Output) Conf_Variables.append(Configuration_Output) ############### Search in Configuration if any command error and return its IP ################ for y in Conf_Variables: if "% Invalid input detected at '^' marker." in y: FailedIps.append(ip + " Invalid input") ######################################################################################################### # Configuration_Output+=Configuration_Switch # Configuration_Output+=Configuration_Router Hostname_Output_list.append(Hostname_Output) test = Configuration_Switch test += Configuration_Output test += Configuration_Router Configuration_Output_list.append(test) Configuration_Output_ID2_list.append(Configuration_Output_ID2) Configuration_Output_ID254_list.append(Configuration_Output_ID254) ############### SAVE Output IN FILES ####################### Global_Output.append(Hostname_Output) net_connect.disconnect() ################### Exception ################################### except socket_error as socket_err: ################ Print error from msg from the main Lib print(f"Socket Error: \n{socket_err}\t for IP {ip}\n") print("Continue") if '111' in f"Type {socket_err}": Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Socket or connection type Error") return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) if '113' in f"Type {socket_err}": FailedIps.append(ip + " No route to the host") return ConfigurationTest_Boolen == 1 return ConfigurationTest_Boolen == 1 except paramiko.ssh_exception.BadHostKeyException as badHostKeyException: ################ Print error from msg from the main Lib print( f"Unable to verify server's host key: \n{badHostKeyException}\n" ) except paramiko.ssh_exception.NoValidConnectionsError as noValidConnectionsError: ################ Print error from msg from the main Lib print(f"no Valid Connections Error: \n{noValidConnectionsError}\n") except (NetMikoAuthenticationException ) as netmikoAuthenticationException: # print ('Authentication Failure\t' + ip) print( str(User_Pass_Num) + " " + str(Username_Device[User_Pass_Num]) + " failed Authentication\t" + ip) ################ Print error from msg from the main Lib print( f"netmikoAuthenticationException : {netmikoAuthenticationException}\n" ) User_Pass_Num += 1 # If it tried all users and pass and failed add it to failedIps if User_Pass_Num >= len(Username_Device): FailedIps.append(ip + " Authentication Error ") # if User_Pass_Num < len(Username_Device) : # print("this is Authentication "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) # Recursive function return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (NetMikoTimeoutException) as netmikoTimeoutException: # print ('Timeout Failure\t' + ip) print(str(Device_Type_Num) + "\tTimeoutException\t" + ip) ################ Print error from msg from the main Lib print(f"netmikoTimeoutException : \n{netmikoTimeoutException}\n") Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Timeout Error") # if Device_Type_Num < len(Device_Type) : # print("this is Timeout "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (paramiko.ssh_exception.SSHException) as sshException: # print ('SSH Failure\t' + ip) print(str(Device_Type_Num) + "\tSSHException\t" + ip + "\n") ################ Print error from msg from the main Lib print( f"Unable to establish SSH connection: \n{sshException}\t for IP {ip}\n" ) Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " SSHException Error ") # if Device_Type_Num < len(Device_Type) : # print("this is SSHException "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (ValueError): print( str(Passowrd_Enable_Num) + " " + str(Passowrd_Device_Enable[Passowrd_Enable_Num]) + " Failed Enable Authentication\t" + ip) Passowrd_Enable_Num += 1 if Passowrd_Enable_Num >= len(Passowrd_Device_Enable): FailedIps.append(ip + " Enable Authentication Error ") return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (EOFError) as eof_Error: ################ Print error from msg from the main Lib print(f"eof_Error : \n{eof_Error}\n") # print ('End of File wihle attempting device\t' +ip) FailedIps.append(ip + " EOFError") # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest_Boolen == 1 #################################################################### ########## if you want to show error , comment next lines if you want to show which Ips have error remove comment ############## #################################################################### except Exception as e: # print ('End of File wihle attempting device\t' +ip) FailedIps.append(ip + " Exception as e") # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest_Boolen == 1 #################################################################### return ConfigurationTest_Boolen == 1
from netmiko import ConnectHandler import yaml from datetime import datetime from getpass import getpass import time password = getpass() devices = yaml.load(open('/home/dkhorn/.netmiko.yml')) cisco4 = devices.get('cisco4') cisco4.update({"password": password,"secret": password,"session_log": "my_output.txt"}) net_conncet = ConnectHandler(**cisco4) output_a = net_conncet.find_prompt() print (output_a) output_b = net_conncet.config_mode() print (net_conncet.find_prompt()) output_c = net_conncet.exit_config_mode() print (net_conncet.find_prompt()) output_d = net_conncet.write_channel("disable\n") time.sleep(2) print(net_conncet.read_channel()) output_e = net_conncet.enable() print (net_conncet.find_prompt())