def push_config_commands(username, password, ip_address, vendor_class, secret, commands): try: net_connect = ConnectHandler(device_type=vendor_class, ip=ip_address, username=username, password=password, secret=secret) net_connect.enable() output = net_connect.send_config_set(commands) print output except: print 'Error in either connecting or executing configuration command @ ' + ip_address
def write_descr(ip, username, password, enable_secret, localint, descr): ssh_connection = ConnectHandler( device_type = 'cisco_ios', ip = ip, username = username, password = password, secret = enable_secret ) ssh_connection.enable() rt = ssh_connection.find_prompt() + "\n" rt = ssh_connection.send_command("conf t", delay_factor=0) rt = ssh_connection.send_command("int "+localint, delay_factor=0) rt = ssh_connection.send_command("description "+descr, delay_factor=0) ssh_connection.disconnect()
def show_version(current_device): device_ip = socket.gethostbyname(current_device) command = "show version" net_connect = ConnectHandler( device_type=device_type, ip=device_ip, username=current_operator.username, password=current_operator.password ) net_connect.find_prompt() net_connect.enable() output = net_connect.send_command(command) return (output)
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 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 get_cdp_neighbor_details(ip, username, password, enable_secret): """ get the CDP neighbor detail from the device using SSH :param ip: IP address of the device :param username: username used for the authentication :param password: password used for the authentication :param enable_secret: enable secret :return: """ # establish a connection to the device ssh_connection = ConnectHandler( device_type='cisco_ios', ip=ip, username=username, password=password, secret=enable_secret ) # enter enable mode ssh_connection.enable() # prepend the command prompt to the result (used to identify the local device) result = ssh_connection.find_prompt() + "\n" # execute the show cdp neighbor detail command # we increase the delay_factor for this command, because it take some time if many devices are seen by CDP result += ssh_connection.send_command("show cdp neighbor detail", delay_factor=2) # close SSH connection ssh_connection.disconnect() return result
def main(): """ This will run an command via serial on an cisco ios switch and so serial cable must be attached to the device """ serialhandle = { "device_type": "cisco_ios_serial", "port": "USB Serial", # can be COM<number> or any line you can get from # serial.tools.list_ports.comports() "username": "******", "password": "******", "secret": "<secret>", "serial_settings": { # this are the default values "baudrate": 9600, "bytesize": serial.EIGHTBITS, "parity": serial.PARITY_NONE, "stopbits": serial.STOPBITS_ONE, }, } net_connect = ConnectHandler(**serialhandle) net_connect.enable() output = net_connect.send_command("show run") net_connect.disconnect() print(output)
def main(): ''' This will run an command via serial on an cisco ios switch and so serial cable must be attached to the device ''' serialhandle = { 'device_type':'cisco_ios_serial', 'port': 'USB Serial', # can be COM<number> or any line you can get from # serial.tools.list_ports.comports() 'username':'******', 'password':'******', 'secret':'<secret>', 'serial_settings':{ # this are the default values 'baudrate': 9600, 'bytesize': serial.EIGHTBITS, 'parity': serial.PARITY_NONE, 'stopbits': serial.STOPBITS_ONE } } net_connect = ConnectHandler(**serialhandle) net_connect.enable() output = net_connect.send_command('show run') net_connect.disconnect() print(output)
def main(): device_list = [cisco_ios, cisco_xr, arista_veos] start_time = datetime.now() print for a_device in device_list: as_number = a_device.pop('as_number') net_connect = ConnectHandler(**a_device) net_connect.enable() print "{}: {}".format(net_connect.device_type, net_connect.find_prompt()) if check_bgp(net_connect): print "BGP currently configured" remove_bgp_config(net_connect, as_number=as_number) else: print "No BGP" # Check BGP is now gone if check_bgp(net_connect): raise ValueError("BGP configuration still detected") # Construct file_name based on device_type device_type = net_connect.device_type file_name = 'bgp_' + device_type.split("_ssh")[0] + '.txt' # Configure BGP output = configure_bgp(net_connect, file_name) print output print print "Time elapsed: {}\n".format(datetime.now() - start_time)
def 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(): inputfile, config_commands = get_cmd_line() print("Switch configuration updater. Please provide login information.\n") # Get username and password information. username = input("Username: "******"Password: "******"Enable Secret: ") print("{}{:<20}{:<40}{:<20}".format( "\n", "IP Address", "Name", "Results"), end="") for switchip in inputfile: ciscosw = { "device_type": "cisco_ios", "ip": switchip.strip(), "username": username.strip(), "password": password.strip(), "secret": enasecret.strip(), } print() print("{:<20}".format(switchip.strip()), end="", flush=True) try: # Connect to switch and enter enable mode. net_connect = ConnectHandler(**ciscosw) except Exception: print("** Failed to connect.", end="", flush=True) continue prompt = net_connect.find_prompt() # Print out the prompt/hostname of the device print("{:<40}".format(prompt), end="", flush=True) try: # Ensure we are in enable mode and can make changes. if "#" not in prompt[-1]: net_connect.enable() print("#", end="", flush=True) except Exception: print("Unable to enter enable mode.", end="", flush=True) continue else: for cmd in config_commands: # Make requested configuration changes. try: if cmd in ("w", "wr"): output = net_connect.save_config() print("w", end="", flush=True) else: output = net_connect.send_config_set(cmd) if "Invalid input" in output: # Unsupported command in this IOS version. print("Invalid input: ", cmd, end="", flush=True) print("*", end="", flush=True) except Exception: # Command failed! Stop processing further commands. print("!") break net_connect.disconnect()
def get_cdp_neighbors(ip, username, password, enable_secret): ssh_connection = ConnectHandler( device_type = 'cisco_ios', ip = ip, username = username, password = password, secret = enable_secret ) ssh_connection.enable() result = ssh_connection.find_prompt() + "\n" result = ssh_connection.send_command("show cdp neighbors", delay_factor=0) with open(os.getcwd()+'/temps/'+ip, 'w') as outfile: outfile.write(result) ssh_connection.disconnect()
def main(): ''' Ansible module to perform config merge on Cisco IOS devices. ''' module = AnsibleModule( argument_spec=dict( host=dict(required=True), port=dict(default=22, required=False), username=dict(required=True), password=dict(required=True), merge_file=dict(required=True), dest_file_system=dict(default='flash:', required=False), ), supports_check_mode=False ) net_device = { 'device_type': 'cisco_ios', 'ip': module.params['host'], 'username': module.params['username'], 'password': module.params['password'], 'port': int(module.params['port']), 'verbose': False, } ssh_conn = ConnectHandler(**net_device) ssh_conn.enable() merge_file = module.params['merge_file'] dest_file_system = module.params['dest_file_system'] # Disable file copy confirmation ssh_conn.send_config_set(['file prompt quiet']) # Perform configure replace cmd = "configure replace {0}{1}".format(dest_file_system, merge_file) output = ssh_conn.send_command(cmd, delay_factor=8) # Enable file copy confirmation ssh_conn.send_config_set(['file prompt alert']) if 'The rollback configlet from the last pass is listed below' in output: module.exit_json(msg="The new configuration has been loaded successfully", changed=True) else: module.fail_json(msg="Unexpected failure during attempted configure replace. " "Please verify the current configuration of the network device.")
def main(): device_list = [cisco_ios, cisco_xr, arista_veos] start_time = datetime.now() print for a_device in device_list: net_connect = ConnectHandler(**a_device) net_connect.enable() print "{}: {}".format(net_connect.device_type, net_connect.find_prompt()) if check_bgp(net_connect): print "BGP currently configured" else: print "No BGP" print print "Time elapsed: {}\n".format(datetime.now() - start_time)
def main(): ''' Connects to router and switches to config mode ''' pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.enable() pynet_rtr2.config_mode() ''' Checks to see if you are in enable mode and prints results to screen ''' if pynet_rtr2.check_config_mode() is True: output = pynet_rtr2.find_prompt() print output else: print 'You are NOT in config mode'
def main(): ''' Ansible module to perform config merge on Cisco IOS devices. ''' module = AnsibleModule( argument_spec=dict( host=dict(required=True), port=dict(default=22, required=False), username=dict(required=True), password=dict(required=True), merge_file=dict(required=True), dest_file_system=dict(default='flash:', required=False), ), supports_check_mode=False ) net_device = { 'device_type': 'cisco_ios', 'ip': module.params['host'], 'username': module.params['username'], 'password': module.params['password'], 'port': int(module.params['port']), 'verbose': False, } ssh_conn = ConnectHandler(**net_device) ssh_conn.enable() merge_file = module.params['merge_file'] dest_file_system = module.params['dest_file_system'] # Disable file copy confirmation ssh_conn.send_config_set(['file prompt quiet']) # Perform config merge cmd = "copy {0}{1} running-config".format(dest_file_system, merge_file) output = ssh_conn.send_command(cmd) # Enable file copy confirmation ssh_conn.send_config_set(['file prompt alert']) if ' bytes copied in ' in output: module.exit_json(msg="File merged on remote device", changed=True) else: module.fail_json(msg="Unexpected failure during attempted config merge. " "Please verify the current configuration on the network device.")
def bootstrapper(dev_type, dev_ip, dev_un, dev_pw, config): try: config_file = open(config, 'r') config_lines = config_file.read().splitlines() config_file.close() open_connection = ConnectHandler(device_type=dev_type, ip=dev_ip, username=dev_un, password=dev_pw) open_connection.enable() output = open_connection.send_config_set(config_lines) print(output) open_connection.send_command_expect('write memory') open_connection.disconnect() return True except: return False
def get_info(device, username, password): dev_config = 'none' try: net_connect = ConnectHandler(device_type='cisco_ios', ip=device, username=username, password=password, secret=password) net_connect.enable() net_connect.send_command('terminal length 0') dev_config = net_connect.send_command('show run') net_connect.exit_enable_mode() net_connect.disconnect() return dev_config except: with open("error_devices.txt", '+a') as errlog: errlog.write("error connecting to " + device + "\n") return dev_config
def find_ip_masks(ip_address): global net_connect advertized_address = [] iosv = connection(ip_address) print("connecting to " + str(iosv)) net_connect = ConnectHandler(**iosv) net_connect.enable() commands = ['exit', 'sh run | include interface|ip address'] output = net_connect.send_config_set(commands, delay_factor=5) addresses = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", output) commands = ['exit', 'sh run'] output = net_connect.send_config_set(commands, delay_factor=6) hostname = re.findall(r'hostname\s+(\S*)', output)[0].encode() visited_list.append(hostname) for a in addresses: address = a.encode('ascii', 'ignore') advertized_address.append(address) return advertized_address
def runner(ipp, u_name, p_word, s_word): ssh_connection = ConnectHandler(device_type='linux', ip=ipp, username=u_name, password=p_word, secret=s_word) ssh_connection.enable() ssh_connection.send_command("clish") print("clish worked") result = ssh_connection.find_prompt() + "\n" result += ssh_connection.send_command("sh run", delay_factor=2) ssh_connection.disconnect() #print(result) return result
def routers_connection(): routers = device_route_map.keys() params = { "username": "******", "password": "******", "secret": "cisco", "device_type": "cisco_ios", "fast_cli": True, } connections = {} for ip in routers: params["host"] = ip ssh = ConnectHandler(**params) ssh.enable() connections[ip] = ssh yield connections for r in connections.values(): r.disconnect()
def gethostname(device): dev = { 'device_type': platform, 'ip': device, 'username': username, 'secret': password, 'password': password, 'global_delay_factor': 4, 'verbose': True, } device = ConnectHandler(**dev) device.enable() hostname = device.send_config_set(command) hostname += device.commit(confirm=True, confirm_delay=5) time.sleep(30) hostname += device.commit(check=True) return hostname
def sendData(self): #print('Intentará crear la conexión con: ', cisco, ' primer instruccion: ', self.cmd[0]) net_connect = ConnectHandler(**cisco) #print('Se hizo la conexión') net_connect.enable() self.cmd = self.cmd #print('Conexión hecha con los datos', self.cmd) print('Direccion que recibe: ', self.cmd[0]) output = net_connect.send_command_timing( f'show cdp entry {self.cmd[0]} | i IP address').split() print('Datos del output: ', output) self.cmd[1] = self.cmd[1] + output[2] output = [] for i in range(1, len(self.cmd)): print('Comando a anotar: ', self.cmd[i]) output.append(net_connect.send_command_timing(self.cmd[i])) return output
def bootstrapper(dev_type, dev_ip, dev_un, dev_pw, config): try: config_file = open(config, 'r') # open the file object described by config argument config_lines = config_file.read().splitlines() # create a list of the file lines without \n config_file.close() # close the file object open_connection = ConnectHandler(device_type=dev_type, ip=dev_ip, \ username=dev_un, password=dev_pw) open_connection.enable() # this sets the connection in enable mode # pass the config to the send_config_set() method output = open_connection.send_config_set(config_lines) print(output) # print the config to the screen # output to the screen open_connection.send_command_expect('write memory') # write the memory (okay if this gets done twice) open_connection.disconnect() # close the open connection return True # Everything worked! - "Return TRUE when complete" except: return False # Something failed during the configuration process - "Return FALSE if fails"
def main(): device_list = [csrv1, csrv2, csrv3] print "\n CONFIGURING NTP PROTOCOL " print for a_device in device_list: net_connect = ConnectHandler(**a_device) net_connect.enable() device_type = net_connect.device_type file_name = "ntp_" + (a_device['username']) + ".txt" print "\n Reading file : " print " {}\n".format(file_name) # Configure NTP ntpconfig = configure_ntp(net_connect, file_name) print ntpconfig print print "\n CLOCK TIMING" output = net_connect.send_command("show clock") print output
def pulltables(brasip, username, password, vpdntables, device_type='cisco_ios_telnet'): session = ConnectHandler(device_type='cisco_ios_telnet', ip=brasip, username=username, password=password) #loggedin = timeit.default_timer() session.enable() #enabled = timeit.default_timer() session.send_command('terminal size 0') vpdn = session.send_command('show vpdn session all') vpdntables.append(vpdn) #gottable = timeit.default_timer() #print(vpdn) session.disconnect()
def dnac_telnet_set2(self, con): cur = con.cursor() print("Telnet check on DNAC topology devices") cur.execute('select ipaddress, username, password, enablepassword from DEVICES where topology="DNAC-TOP-2"') devicelist = [value for value in cur] for value in devicelist: print(value) try: device = ConnectHandler(device_type='cisco_ios_telnet', ip=value[0], username=value[1], password=value[2], secret=value[3]) device.enable() cur.execute('update DEVICES set telnetstatus="Reachable" where ipaddress=? and topology="DNAC-TOP-2"', [value[0]]) con.commit() print("Device Connected") device.disconnect() except Exception as e: print(e) cur.execute('update DEVICES set telnetstatus="Unreachable" where ipaddress=? and topology="DNAC-TOP-2"', [value[0]]) con.commit()
def main(): devices = { 'device_type': 'cisco_ios', 'ip': 'xxxxx', 'username': '******', 'password': getpass.getpass(), 'port': 22, 'secret': 'cisco' } #Create The Connection Handle Object connection = ConnectHandler(**devices) #Enter Into Enable Mode connection.enable() # Configure the Devices From a File. connection.send_config_from_file('ospf.txt') #Close The Connection connection.disconnect()
def sshsession(): net_connect = ConnectHandler(device_type='cisco_ios', ip='192.168.122.11', username='******', password='******', secret='cisco') print(net_connect.find_prompt()) print(net_connect.enable()) return net_connect
def config(device1,input,output,vlan_id): try: device2 = {"ip":"","username":"","password":"","device_type":"","secret":""} device2 ['ip'] = device1["ip"] device2 ['username'] = device1 ["username"] device2 ['password'] = device1 ["password"] device2 ['secret'] = device1 ["secret"] device2 ['device_type'] = device1 ["device_type"] port1 = input port2 = output port = [] vlanId = vlan_id connection = ConnectHandler(**device2) connection.enable() out1 = connection.send_command('show interfaces description') InterfaceInf = CheckInterface(out1) portValid = InterfaceInf port = [port1,port2] for i in port: if i in InterfaceInf: words = [] output1 = connection.send_command('show running-config interface '+i) words = pars(output1) if len(words) == 0: config1 = ['interface '+i,'switchport trunk enc dot1q','switchport mode trunk','switchport trunk allowed vlan '+vlanId,'sp mode ra','sp vlan '+vlanId] sw_output = connection.send_config_set(config1) else: config1 = ['interface '+i,'switchport trunk enc dot1q','switchport mode trunk','switchport trunk allowed vlan add '+vlanId,'sp mode ra','sp vlan '+vlanId] sw_output = connection.send_config_set(config1) else: print("The interface {} is wrong.Please check the information again".format(i)) print('~'*79) my_thread.do_run = False exit(1000) connection.enable() connection.send_command('write memory') connection.disconnect() print ('The connection to {} is disconnected'.format(device2['ip'])) print('~'*79) except netmiko_exceptions as e: print('failed to ',device2['ip'],e) exit(3)
def _backup_config_to_tftp_server(): year_month_day = _get_ymd_currently() hour_munites_second = _get_hms_currently() mode_enable = 'enable' mode_configure_system = 'configure system' file_name_router_backup = '192.168.1.1-V3900-1.5.1-' + year_month_day + '-' + hour_munites_second + '.tgz' command_backup_file_config_tftp = 'config backup 192.168.1.3 ' + file_name_router_backup path_sub_directory_tftp_server = '/router1-vigor-draytek3k9/config-' + year_month_day + '/' start_time = datetime.now() try: net_connect_device = ConnectHandler(**vigor_draytek_3900) net_connect_device.enable() result_run_command = net_connect_device.send_command( mode_enable, expect_string=r'Entering enable mode...') result_run_command += net_connect_device.send_command( mode_configure_system, expect_string=r'#') result_run_command += net_connect_device.send_command( command_backup_file_config_tftp, expect_string=r'#') print(result_run_command) print(file_name_router_backup) time.sleep(10) print(file_name_router_backup) end_time = datetime.now() print("Total time backup startup config: {}".format(end_time - start_time)) CONTENT_DETAIL = '#BackupConfig #RouterVigor #Draytek3900 #TftpServer #Done\nIP Router: 192.168.1.1\nJob status: Ok\n' send_api_telegram_bot_true(CONTENT_DETAIL) net_connect_device.disconnect() command_move_backup_file_config_tftp = 'mv /tftpdata/192.168.1.1-V3900-1.5.1-* /tftpdata' + path_sub_directory_tftp_server os.system(command_move_backup_file_config_tftp) except NetMikoTimeoutException as error: CONTENT_DETAIL = '#BackupConfig #RouterVigor #Draytek3900 #TftpServer #ConnectingTimeOut\nIP Router: 192.168.1.1\nJob status: Failed\n' CONTENT_DETAIL += str(error) send_api_telegram_bot_failed(CONTENT_DETAIL) return None except NetMikoAuthenticationException as error: CONTENT_DETAIL = '#BackupConfig #RouterVigor #Draytek3900 #TftpServer #AuthenticationFailed\nIP Router: 192.168.1.1\nJob status: Failed\n' CONTENT_DETAIL += str(error) send_api_telegram_bot_failed(CONTENT_DETAIL) return None
def _cisco_push(user, password, ip, command_list, device_type="cisco_ios"): """ This function helps to push configurations inside Cisco IOS devices. """ device = { 'device_type': device_type, 'ip': ip, 'username': user, 'password': password, 'secret': password } try: net_connect = ConnectHandler(**device) net_connect.enable() net_connect.send_config_set(command_list) output = net_connect.send_command_expect(SHOW_RUN) print "Configuration pushed!" return output except: print "ERROR! Something wrong happened during the configuration process." return 0
def Sricity(my_ip): my_dev = { 'host': my_ip, 'username': login.username, 'password': login.password, 'secret': login.password, 'device_type': 'cisco_ios' } session = ConnectHandler(**my_dev) session.enable() prompt = session.find_prompt() output = session.send_command('show spanning-tree vlan 1-1000 summary', expect_string=prompt, delay_factor=10) # filename = f"{my_ip}_cisco.txt" with open('INHY4_2.txt', 'a') as f: f.writelines(prompt + '' + my_ip + '\n' + output + '\n' + '\n' + '\n') session.disconnect()
def delete_vlan(self): list = devicelist.objects.all() vlanlist = vlans.objects.all() net_connect = ConnectHandler(device_type=list.get(name=self.hostname).devicetype, host=list.get(name=self.hostname).host, username=list.get(name=self.hostname).username, password=list.get(name=self.hostname).password, secret=list.get(name=self.hostname).secret) net_connect.enable() config_commands = ["no vlan "+self.vlanNum] net_connect.send_config_set(config_commands) output = net_connect.send_command('show vlan b') net_connect.disconnect() vlanlist.filter(name=self.hostname,vlanNum=self.vlanNum).delete() TEMP_FILE = "templates/query_vlans_model" fsm = textfsm.TextFSM(open(TEMP_FILE)) input_txt = output fsm_results = fsm.ParseText(input_txt) return fsm_results
def configure_bgp(net_connect, file_name=''): """Configure BGP on device.""" file_num = 0 for device in device_list: file_num +=1 # Iteration to keep the BGP commands file's number device_type = net_connect.device_type print("\tConnecting {} : {}".format(device_type,device['ip'])) file_name = 'bgp_' + device_type.split("_ssh")[0]+ str(file_num) + '.txt' #generates filename with file numbers print("\tReading from the file : {} ".format(file_name)) as_number = device.pop('as_number') # Removing AS number net_connect = ConnectHandler(**device) net_connect.enable() # Entering enable mode try: output = net_connect.send_config_from_file(config_file=file_name) #Sending commands from the file to the device print (output) except IOError: print ("Error reading file: {}".format(file_name)) device['as_number'] = as_number # Adding back AS number for other functions
def delete_route(self): list = devicelist.objects.all() routelist = routes.objects.all() net_connect = ConnectHandler(device_type=list.get(name=self.hostname).devicetype, host=list.get(name=self.hostname).host, username=list.get(name=self.hostname).username, password=list.get(name=self.hostname).password, secret=list.get(name=self.hostname).secret) net_connect.enable() config_commands = ['no ip route ' + self.net + ' ' + self.netmask] net_connect.send_config_set(config_commands) output = net_connect.send_command('show ip route') net_connect.disconnect() routelist.filter(name=self.hostname, route=self.net+'/24').delete() TEMP_FILE = "templates/query_routes_model" fsm = textfsm.TextFSM(open(TEMP_FILE)) input_txt = output fsm_results = fsm.ParseText(input_txt) return fsm_results
def config(): #create an Empty Dictionary newdeviceDic = {} #Create a List of Device IPs ips = devIps() for ip in ips: newdeviceDic = setDeviceType(ip, newdeviceDic={}) # Create The Connection Object configurations = ConnectHandler(**newdeviceDic) try: for ip in ips: # Place in Enable Mode configurations.enable() #Configure the Devices From A File IT will Automatically Enter the Configuration mode and Send the CMDs configurations.send_config_from_file('ospf.txt') #Close The Configurations configurations.disconnect() except Exception as e: print(e)
def findmac(username, password, secret): with open(customer, mode='r') as csvfile: reader = csv.DictReader(csvfile) macAddr = input('MAC of the device in cisco format: ') command_string_mac = 'show mac add | inc ' + str(macAddr) command_string_cdp = 'show cdp neigh | inc ' + str(macAddr) for row in reader: hostname = row['SysName'] device_type = row['device_type'] ip = row['IP_Address'] switch = { 'device_type': device_type, 'ip': ip, 'username': username, 'password': password, 'secret': secret, 'verbose': False, } net_connect = ConnectHandler(**switch) net_connect.enable() macreturn = net_connect.send_command(command_string_mac) cdpreturn = net_connect.send_command(command_string_cdp) print("\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(row['SysName'])) print("\nMAC Address Hits on this switch: ") print(macreturn) print("\nCisco Discovery Protocol Hits on this switch: ") if cdpreturn == "": print("No CDP results for this MAC") else: print(cdpreturn) cdplist = ' '.join(macreturn.split()) port = cdplist.split(' ')[3] command_string_port = 'show run int ' + str(port) portreturn = net_connect.send_command(command_string_port) print("\nPort Configuration for matched CDP: ") print(portreturn) print("\n>>>>>>>>> End <<<<<<<<<") net_connect.disconnect()
def creat_route(self): list = devicelist.objects.all() net_connect = ConnectHandler(device_type=list.get(name=self.hostname).devicetype, host=list.get(name=self.hostname).host, username=list.get(name=self.hostname).username, password=list.get(name=self.hostname).password, secret=list.get(name=self.hostname).secret) net_connect.enable() config_commands = ['ip route '+self.net+' '+self.netmask+" "+self.nexthop] net_connect.send_config_set(config_commands) output = net_connect.send_command('show ip route') net_connect.disconnect() i = routes(name = self.hostname,routetag='S',route=self.net+"/24",nexthop=self.nexthop) i.save() TEMP_FILE = "templates/query_routes_model" fsm = textfsm.TextFSM(open(TEMP_FILE)) input_txt = output fsm_results = fsm.ParseText(input_txt) return fsm_results
def run_task(a_device): try: host = a_device['host'] a_result = {} a_result['host'] = host start_time = datetime.now() remote_conn = ConnectHandler( device_type=a_device['device_type'], host=a_device['host'], username=a_device['username'], password=a_device['password'], port=22, secret=a_device['secret'], #fast_cli=True ) remote_conn.enable() #remote_conn.fast_cli = False data = remote_conn.send_command('show running-config') remote_conn.disconnect() elapsed_time_ssh = datetime.now() - start_time a_result['ssh_runtime'] = elapsed_time_ssh data = config_filter_cisco_ios(data) if a_device['device_type'] == 'cisco_ios': data = re.sub(r'^\s*$', "", data, flags=re.M) with open(f"configs/{host}.cfg", "w") as f: f.write(data) return a_result except Exception as e: print(f'** {host} task closing with error {e}') a_result['exception'] = e a_result['traceback'] = traceback.format_exc() return a_result
def netmiko_connection(self, device: "Device") -> ConnectHandler: if self.parent_runtime in app.connections_cache["netmiko"]: parent_connection = app.connections_cache["netmiko"].get( self.parent_runtime ) if parent_connection and device.name in parent_connection: if self.job.start_new_connection: parent_connection.pop(device.name).disconnect() else: connection = parent_connection[device.name] try: connection.find_prompt() for property in ("fast_cli", "timeout", "global_delay_factor"): setattr(connection, property, getattr(self.job, property)) mode = connection.check_enable_mode() if mode and not self.privileged_mode: connection.exit_enable_mode() elif self.privileged_mode and not mode: connection.enable() return connection except (OSError, ValueError): self.disconnect("netmiko", device, connection) parent_connection.pop(device.name) username, password = self.get_credentials(device) driver = device.netmiko_driver if self.use_device_driver else self.driver netmiko_connection = ConnectHandler( device_type=driver, ip=device.ip_address, port=getattr(device, "port"), username=username, password=password, secret=device.enable_password, fast_cli=self.fast_cli, timeout=self.timeout, global_delay_factor=self.global_delay_factor, ) if self.privileged_mode: netmiko_connection.enable() app.connections_cache["netmiko"][self.parent_runtime][ device.name ] = netmiko_connection return netmiko_connection
def send_config_command(device, comm, verbose = True): good = {} bad = {} if verbose: print('connection to device {}'.format(device['ip'])) device_params = device try: ssh = ConnectHandler(**device_params) ssh.enable() for comm in commands: result = ssh.send_config_set(comm) if 'Incomplete command' in result: print ('Команда \"{}\" выполнилась с ошибкой "Incomplete command." на устройстве {}'.format(comm, device['ip'])) bad[comm] = result ui = input('Continue? [Y/N] ') if ui.lower() in ('y', 'yes'): continue elif ui.lower() in ('n', 'no'): break elif 'Invalid input' in result: print ('Команда \"{}\" выполнилась с ошибкой "Invalid input detected at \'^\' marker." на устройстве {}'.format(comm, device['ip'])) bad[comm] = result ui = input('Continue? [Y/N] ') if ui.lower() in ('y', 'yes'): continue elif ui.lower() in ('n', 'no'): break else: good[comm] = result except netmiko.ssh_exception.SSHException as err: print (err) result2 = good, bad pprint(result2, width=120)
def funcfeat1(): my_dns_server_ip = DNS_IP() file_push = sys.argv[1] file_push_gen = "rfc_" + str(file_push) domain = { 'device_type': "linux", 'ip': str(my_dns_server_ip), 'username': "******", 'password': "******", 'secret': 'root' } net_connect = ConnectHandler(**domain) net_connect.enable() op1 = net_connect.send_command_timing("python3 /home/dns_pub.py " + str(file_push_gen) + " " + DNS_server) #op1 = net_connect.send_command_timing("python3 /home/dns_pub.py " + str(file_push_gen) + " " + str(my_ip_add)) ES_list = [] ES_list.append(op1.split('\n')[-1]) ES_list.append(op1.split('\n')[-2]) ES_list.append(root_cdn.split('/')[0]) print(ES_list) #print(ES_list) '''paramiko for the two ips of op1''' for each_ip in ES_list: #print(each_ip) ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #print(each) ssh_client.connect(hostname=str(each_ip), username='******', password='******') ftp_client = ssh_client.open_sftp() #print("/home/cdn_data/" + str(file_push_gen) + ".txt,"+"/home/cdn_data/" + str(file_push_gen) + ".txt") a1 = "/home/cdn_data/" + str(file_push_gen) + ".txt" #print(a1) ftp_client.put(a1, a1) ftp_client.close() ssh_client.close()
class SSHClient(object): def __init__(self): self.ssh = None def login_host(self, device): """ 定义login_host函数,用于登陆设备 :param device: :return: """ try: self.ssh = ConnectHandler(**device) self.ssh.enable() reply = self.ssh.find_prompt() print('>' * 10 + '成功登陆结果如下:' + '>' * 10 + '\n' + reply) return True except ValueError: logging.warning(device['host'] + ' Secret 密码错误') except NetMikoTimeoutException: logging.warning(device['host'] + ' 连接不上设备,请检查网络是否正常通信') except NetMikoAuthenticationException: logging.warning(device['host'] + ' 登录失败,用户名或密码错误') def do_cmd(self, cmds): """ 定义do_cmd函数,用于执行命令 :param cmds: :return: """ with open(cmds) as cmd_obj: for cmd in cmd_obj: reply = self.ssh.send_command(cmd) time.sleep(1) logging.warning('>' * 10 + cmd.rstrip() + ' 命令执行结果如下:' + '>' * 10 + '\n' + reply) def logout_host(self): """ 定义logout_host函数,关闭程序 :return: """ self.ssh.disconnect()
class ConfigSSH: def __init__(self, ip, device_type, username, password, secret, hostname): credential = { 'ip': ip, 'device_type': device_type, 'username': username, 'password': password, 'secret': secret, } self.hostname = hostname self.credential = credential self.conn = ConnectHandler(**credential) def backup(self): #if there is any secret password if self.credential['secret'] != None: self.conn.enable() #grab current config config_output = self.conn.send_command('show running-config') result = config_output.replace('\n', '\r') return result def restore(self, config): if self.credential['secret'] != None: self.conn.enable() #create tcl script on router self.conn.send_command('tclsh', expect_string='') self.conn.send_command('puts [open restore-config.conf w+] {\r%s}' % config) self.conn.send_command('tclquit', expect_string='') #restore config to system self.conn.send_command( 'configure replace flash:restore-config.conf\ry\r\r') return True def close(self): self.conn.disconnect()
def main(): device_list = [csrv1, csrv2, csrv3] print "\n CONFIGURING SNMP PROTOCOL " print for a_device in device_list: net_connect = ConnectHandler(**a_device) net_connect.enable() #print "{}: {}".format(net_connect.device_type, net_connect.find_prompt() device_type = net_connect.device_type file_name = "snmp_" + (a_device['username']) + ".txt" print "\n Reading file : " print " {}\n".format(file_name) # Configure SNMP snmpconfig = configure_snmp(net_connect, file_name) print snmpconfig print
def main(): ''' Logs into each router and collects the arp table ''' print '=' *80 pynet_rtr1 = ConnectHandler(**pynet1) pynet_rtr1.enable() output = pynet_rtr1.send_command('show arp') print '\nShow arp from pynet1\n' +output print print '=' *80 pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.enable() output = pynet_rtr2.send_command('show arp') print '\nShow arp from pynet2\n' +output print print '=' *80 pynet_srx1 = ConnectHandler(**pynetsrx1) output = pynet_srx1.send_command('show arp') print '\nShow arp from SRX' +output
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 setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'RP/0/0/CPU0:XRv-1#', 'base_prompt' : 'RP/0/0/CPU0:XRv-1', 'interface_ip' : '169.254.254.181', 'config_mode' : '(config)' } show_ver_command = 'show version' commit_history_cmd = 'show configuration commit list' module.basic_command = 'show ipv4 int brief' net_connect = ConnectHandler(**cisco_xr) 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() current_commit_history = net_connect.send_command(commit_history_cmd) # get the current 10 digit commit Label ID module.current_commit = current_commit_history.split('\n')[4].split()[1] module.config_mode = net_connect.config_mode() config_commands = ['logging monitor warning', 'logging buffered 30720100', 'logging console errors'] net_connect.send_config_set(config_commands) net_connect.commit() # get the new 10 digit commit Label ID new_commit_history = net_connect.send_command(commit_history_cmd) module.new_commit = new_commit_history.split('\n')[4].split()[1] module.config_commands_output = net_connect.send_command("show run | inc logging") net_connect.disconnect()
def main(): module = AnsibleModule( argument_spec=dict( host=dict(required=True), port=dict(default=22, required=False), username=dict(required=True), password=dict(required=True), source_file=dict(required=True), target_dir=dict(required=False, default="flash"), target_name=dict(required=False, default=False), protocol=dict(required=True), host_url=dict(required=True) ), supports_check_mode=False ) source_file = module.params['source_file'] target_name = module.params['target_name'] if(not target_name): target_name=source_file target_dir = module.params['target_dir'] host_url = module.params['host_url'] protocol = module.params['protocol'] + "://" net_device = { 'device_type': 'cisco_ios', 'ip': module.params['host'], 'username': module.params['username'], 'password': module.params['password'], 'port': int(module.params['port']), 'verbose': False, } ssh_conn = ConnectHandler(**net_device) output=ssh_conn.enable() output = ssh_conn.send_command_expect("copy " + protocol+host_url + "/" + source_file+" " + target_dir + ":" + target_name,"filename") if("No such file or directory" in output): module.fail_json(msg="Note enough space on device",changed=False) output = ssh_conn.send_command(target_name) if("Not enough space on device" in output): module.fail_json(msg="Note enough space on device",changed=False) while(True): newoutput = ssh_conn.find_prompt() if "!" not in newoutput: break time.sleep(5) module.exit_json(msg=output,changed=True)
def main(): module = AnsibleModule( argument_spec=dict( connection=dict(choices=['ssh', 'telnet'], default='ssh'), platform=dict(required=False), commands=dict(required=False, type='list'), commands_file=dict(required=False), host=dict(required=False), port=dict(required=False), provider=dict(type='dict', required=False), username=dict(required=False, type='str'), password=dict(required=False, type='str'), secret=dict(required=False, type='str'), use_keys=dict(required=False, default=False, type='bool'), key_file=dict(required=False, default=None, type='str'), ), supports_check_mode=False ) provider = module.params['provider'] or {} # allow local params to override provider for param, pvalue in provider.items(): module.params[param] = module.params.get(param, None) or pvalue host = module.params['host'] connection = module.params['connection'] platform = module.params['platform'] device_type = platform.split('-')[0] commands = module.params['commands'] commands_file = module.params['commands_file'] username = module.params['username'] password = module.params['password'] secret = module.params['secret'] use_keys = module.params['use_keys'] key_file = module.params['key_file'] argument_check = { 'host': host, 'username': username, 'platform': platform, 'password': password } for key, val in argument_check.items(): if val is None: module.fail_json(msg=str(key) + " is required") if module.params['host']: host = socket.gethostbyname(module.params['host']) if connection == 'telnet' and platform != 'cisco_ios': module.fail_json(msg='only cisco_ios supports ' 'telnet connection') if platform == 'cisco_ios' and connection == 'telnet': device_type = 'cisco_ios_telnet' if module.params['port']: port = int(module.params['port']) else: if connection == 'telnet': port = 23 else: port = 22 if connection in ['ssh', 'telnet']: device = ConnectHandler(device_type=device_type, ip=socket.gethostbyname(host), port=port, username=username, password=password, secret=secret, use_keys=use_keys, key_file=key_file ) if secret: device.enable() if commands: output = device.send_config_set(commands) else: try: if commands_file: if os.path.isfile(commands_file): with open(commands_file, 'r') as f: output = device.send_config_set(f.readlines()) except IOError: module.fail_json(msg="Unable to locate: {}".format(commands_file)) if (error_params(platform, output)): module.fail_json(msg="Error executing command:\ {}".format(output)) results = {} results['response'] = output module.exit_json(changed=True, **results)
#!/usr/bin/python from netmiko import ConnectHandler from DEVICE_CREDS import * # DEVICE_CREDS.py is just a dictionary which represts the devices' properties # can use "dir()" to check imported directories cisco_conn = ConnectHandler(**cisco_881) # make ssh connections to devices listed in DEVICE_CREDS.py arista_conn = ConnectHandler(**arista_veos_sw) hp_conn = ConnectHandler(**hp_procurve) cisco_conn.enable() # after connect to devices successfully, for example, to cisco_881 # user "find_prompt()" method to check the cisco CLI status: # (in python interface) # >>> cisco_conn.find_prompt() # >>> 'cisco_881> ' # # Then user "enable()" method to enter the privilege-level CLI: # (in python interface) # >>> cisco_conn.enble() # >>> cisco_conn.filename_upper_camelnd_prompt() # >>> 'cisco_881# ' show_output = cisco_conn.send_command("show ip int bri") print (show_output) # Using "send_command(<cli command>)" method to send CLI commands (which will # not change the configuration) to devices remotely show_output = cisco_conn.send_command("show ip rou | in 10.10.0.0") print (show_output)
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
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()
def main(): module = AnsibleModule( argument_spec=dict( connection=dict(choices=['ssh'], default='ssh'), platform=dict(required=True), commands=dict(required=False, type='list'), commands_file=dict(required=False), host=dict(required=False), port=dict(default=22, required=False), username=dict(required=False, type='str'), password=dict(required=False, type='str'), secret=dict(required=False, type='str'), use_keys=dict(required=False, default=False, type='bool'), key_file=dict(required=False, default=None, type='str'), ), required_together=( ['host', 'password', 'username'], ), supports_check_mode=False ) connection = module.params['connection'] platform = module.params['platform'] device_type = platform.split('-')[0] commands = module.params['commands'] commands_file = module.params['commands_file'] username = module.params['username'] password = module.params['password'] secret = module.params['secret'] use_keys = module.params['use_keys'] key_file = module.params['key_file'] port = int(module.params['port']) if module.params['host']: host = socket.gethostbyname(module.params['host']) if connection == 'ssh' and not module.params['host']: module.fail_json(msg='specify host if using connection=ssh') if connection == 'ssh': device = ConnectHandler(device_type=device_type, ip=socket.gethostbyname(host), port=port, username=username, password=password, secret=secret, use_keys=use_keys, key_file=key_file ) if secret: device.enable() if commands: output = device.send_config_set(commands) try: if commands_file: if os.path.isfile(commands_file): with open(commands_file, 'r') as f: output = device.send_config_set(f.readlines()) except: module.fail_json(msg="Unable to locate: {}".format(commands_file)) if (error_params(platform, output)): module.fail_json(msg="Error executing command:\ {}".format(output)) results = {} results['response'] = output module.exit_json(changed=True, **results)
#!/usr/bin/python import sys import re from netmiko import ConnectHandler #cisco asa instellingen #TODO rsa key of username en password in andere file cisco_5505 = {'device_type':'cisco_asa', 'ip':'193.191.187.41', 'username':'******', 'password': '******', 'secret':'secret', 'verbose': True,} net_connect = ConnectHandler(**cisco_5505) #ssh connection opstarten met de cisco_5505 net_connect.enable() # enable commando net_connect.send_command('\n') #enable password net_connect.send_command('conf t')# execute commando command = ' '.join( sys.argv[1:]) output=net_connect.send_command(command) #all except first newoutput = output.replace("-", "") print newoutput
end_time = datetime.now() # # Get a idea of total time to run on device total_time = end_time - start_time # # Print all out put to file create earlier print >> file, start_time, "\n", end_time, "\n", "total time is", total_time, "\n\n", shoCryptoIsakmp file.close() #######################################Variables########################## all_devices = [cisco_bob, cisco_2960POE, cisco_ASA] customer_name = "OptyxHome" ######################################Script main######################### ##Iterate through devices, connect via SSH, create directory with customer name # # take the time when the script starts start_time = datetime.now() for a_device in all_devices: # # Connect to device net_connect = ConnectHandler(**a_device) # # Enter enable mode net_connect.enable() # # Run ShoRun shoRun() shoVersion() if a_device["device_type"] == "cisco_asa": shoCryptoIsakmp() else: shoCdpNeighd()
class FrroutingDriver(NetworkDriver): """Napalm driver for Frrouting.""" _MINUTE_SECONDS = 60 _HOUR_SECONDS = 60 * _MINUTE_SECONDS _DAY_SECONDS = 24 * _HOUR_SECONDS _WEEK_SECONDS = 7 * _DAY_SECONDS _YEAR_SECONDS = 365 * _DAY_SECONDS def __init__(self, hostname, username, password, timeout=60, optional_args=None): """Constructor.""" self.device = None self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.loaded = False self.changed = False if optional_args is None: optional_args = {} # Netmiko possible arguments netmiko_argument_map = { 'port': None, '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, 'secret': None, 'allow_agent': False } # Build dict of any optional Netmiko args self.netmiko_optional_args = { k: optional_args.get(k, v) for k, v in netmiko_argument_map.items() } self.port = optional_args.get('port', 22) self.sudo_pwd = optional_args.get('sudo_pwd', self.password) def open(self): try: self.device = ConnectHandler(device_type='linux', host=self.hostname, username=self.username, password=self.password, **self.netmiko_optional_args) # Enter root mode. if self.netmiko_optional_args.get('secret'): self.device.enable() except NetMikoTimeoutException: raise ConnectionException('Cannot connect to {}'.format(self.hostname)) except ValueError: raise ConnectionException('Cannot become root.') def close(self): self.device.disconnect() def is_alive(self): return { 'is_alive': self.device.remote_conn.transport.is_active() } def load_merge_candidate(self, filename=None, config=None): if not filename and not config: raise MergeConfigException('filename or config param must be provided.') self.loaded = True if filename is not None: with open(filename, 'r') as f: candidate = f.readlines() else: candidate = config if not isinstance(candidate, list): candidate = [candidate] candidate = [line for line in candidate if line] for command in candidate: if 'sudo' not in command: command = '{0}'.format(command) output = self._send_command(command) if "error" in output or "not found" in output: raise MergeConfigException("Command '{0}' cannot be applied.".format(command)) def discard_config(self): return '' def compare_config(self): if self.loaded: diff = self._send_command('/usr/lib/frr/frr-reload.py --test /etc/frr/frr.conf') return re.sub('\x1b\[\d+m', '', diff) return '' def commit_config(self): if self.loaded: self._send_command('net commit') self.changed = True self.loaded = False def _send_command(self, command): response = self.device.send_command_timing(command) if '[sudo]' in response: response = self.device.send_command_timing(self.sudo_pwd) return response def get_config(self, retrieve='all'): configs = { 'startup': '', 'running': '', 'candidate': '', } if retrieve in ('running', 'all'): command = 'vtysh -c "show running-config"' output = self._send_command(command) configs['running'] = output return configs def get_facts(self): facts = { 'vendor': py23_compat.text_type('FRRouting') } # Get "net show hostname" output. hostname = self.device.send_command('hostname') uptime_output = self._send_command("cat /proc/uptime | awk '{print $1}'") uptime = int(float(uptime_output)) os_version = self._send_command("vtysh -c 'show version'").split("\n") model = self._send_command("lsb_release -d | awk -F':' '{print $2}'").strip() serial_number = "123" iface_list = list() interfaces = self._send_command("vtysh -c 'show interface description'").split("\n") for line in interfaces[1:]: iface_name, status, protocol, description = (line.split() + [""]*99)[:4] iface_list.append(iface_name) facts['hostname'] = facts['fqdn'] = py23_compat.text_type(hostname) facts['os_version'] = py23_compat.text_type(os_version[0]) facts['model'] = py23_compat.text_type(model) facts['uptime'] = int(uptime) facts['serial_number'] = py23_compat.text_type(serial_number) facts['interface_list'] = string_parsers.sorted_nicely(iface_list) return facts def get_arp_table(self): """ '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 """ output = self._send_command('arp -n') output = output.split("\n") output = output[1:] arp_table = list() for line in output: line = line.split() 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._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._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._send_command('vtysh -c "show ip bgp summary"') output = output.split("\n") match = re.search(".* router identifier (\d+\.\d+\.\d+\.\d+), local AS number (\d+)", output[2]) output6 = self._send_command('vtysh -c "show bgp ipv6 summary"') output6 = output6.split("\n") match6 = re.search(".* router identifier (\d+\.\d+\.\d+\.\d+), local AS number (\d+)", output6[2]) 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[9:-2] if i is not ""] bgp_info6 = [i6.strip() for i6 in output6[9:-2] if i6 is not ""] for address_family in ["ipv4", "ipv6"]: peers = [] if address_family == "ipv4": peers = bgp_info elif address_family == "ipv6": peers = bgp_info6 for i in peers: if len(i) > 0: [ peer_id, bgp_version, remote_as, msg_rcvd, msg_sent, table_version, \ in_queue, out_queue, up_time, state_prefix, admin ] = (i.split() + [""]*99)[:11] is_enabled = "(Admin)" not in admin received_prefixes = 0 try: state_prefix = int(state_prefix) received_prefixes = int(state_prefix) is_up = True except ValueError: 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._send_command('vtysh -c "show bgp %s neighbors %s"' % (address_family, 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 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): deadline = timeout * count command = "ping %s " % destination command += "-t %d " % int(ttl) command += "-w %d " % int(deadline) command += "-s %d " % int(size) command += "-c %d " % int(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 ('transmitted' in packet_info[-2]): 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_responses = list() response_info = output_ping.split("\n") for res in response_info: match_res = re.search("from\s([\d\.]+).*time=([\d\.]+)", res) if match_res is not None: ping_responses.append( { "ip_address": match_res.group(1), "rtt": float(match_res.group(2)) } ) 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": ping_responses } return ping_result def get_interfaces(self): output = self._send_command('vtysh -c "show interface"') interface = description = mac_address = speed = speedformat = '' is_enabled = is_up = None last_flapped = -1.0 interface_dict = {} for line in output.splitlines(): interface_regex_1 = r"(\S+?)\s+is\s+(.+?),\s+line\s+protocol\s+is\s+(\S+)" interface_regex_2 = r"^(\S+)\s+is\s+(up|down)" for pattern in (interface_regex_1, interface_regex_2): interface_match = re.search(pattern, line) if interface_match: interface = interface_match.group(1) status = interface_match.group(2) try: protocol = interface_match.group(3) except IndexError: protocol = '' if 'admin' in status.lower(): is_enabled = False else: is_enabled = True if protocol: is_up = bool('up' in protocol) else: is_up = bool('up' in status) break mac_addr_regex = r"^\s+HWaddr:+(.*)" if re.search(mac_addr_regex, line): mac_addr_match = re.search(mac_addr_regex, line) mac_address = napalm_base.helpers.mac(mac_addr_match.groups()[0].strip()) descr_regex = "^\s+Description:\s+(.+?)$" if re.search(descr_regex, line): descr_match = re.search(descr_regex, line) description = descr_match.groups()[0] speed_regex = r"\s+mtu\s+\d+\s+speed\s+(\d+)" if re.search(speed_regex, line): speed_match = re.search(speed_regex, line) speed = speed_match.groups()[0] #speedformat = speed_match.groups()[1] speed = float(speed) #if speedformat.startswith('Kb'): # speed = speed / 1000.0 #elif speedformat.startswith('Gb'): # speed = speed * 1000 speed = int(round(speed)) if interface == '': raise ValueError("Interface attributes were found without any known interface") if not isinstance(is_up, bool) or not isinstance(is_enabled, bool): raise ValueError("Did not correctly find the interface status") interface_dict[interface] = {'is_enabled': is_enabled, 'is_up': is_up, 'description': description, 'mac_address': mac_address, 'last_flapped': last_flapped, 'speed': speed} interface = description = mac_address = speed = speedformat = '' is_enabled = is_up = None return interface_dict def get_interfaces_ip(self): """ Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, 'ipv6': { u'1::1': { 'prefix_length': 64}, u'2001:DB8:1::1': { 'prefix_length': 64}, u'2::': { 'prefix_length': 64}, u'FE80::3': { 'prefix_length': 10}}}, u'Tunnel0': { 'ipv4': { u'10.63.100.9': { 'prefix_length': 24}}}, u'Tunnel1': { 'ipv4': { u'10.63.101.9': { 'prefix_length': 24}}}, u'Vlan100': { 'ipv4': { u'10.40.0.1': { 'prefix_length': 24}, u'10.41.0.1': { 'prefix_length': 24}, u'10.65.0.1': { 'prefix_length': 24}}}, u'Vlan200': { 'ipv4': { u'10.63.176.57': { 'prefix_length': 29}}}} """ interfaces = {} command = 'show interface' show_ip_interface = self._send_command(command) INTERNET_ADDRESS = r'\s+(?:Internet address is|Secondary address)' INTERNET_ADDRESS += r' (?P<ip>{})/(?P<prefix>\d+)'.format(IPV4_ADDR_REGEX) LINK_LOCAL_ADDRESS = r'\s+IPv6 is enabled, link-local address is (?P<ip>[a-fA-F0-9:]+)' GLOBAL_ADDRESS = r'\s+(?P<ip>[a-fA-F0-9:]+), subnet is (?:[a-fA-F0-9:]+)/(?P<prefix>\d+)' interfaces = {} for line in show_ip_interface.splitlines(): if (len(line.strip()) == 0): continue if (line[0] != ' '): ipv4 = {} interface_name = line.split()[0] m = re.match(INTERNET_ADDRESS, line) if m: ip, prefix = m.groups() ipv4.update({ip: {"prefix_length": int(prefix)}}) interfaces[interface_name] = {'ipv4': ipv4} for line in show_ip_interface.splitlines(): if (len(line.strip()) == 0): continue if (line[0] != ' '): ifname = line.split()[0] ipv6 = {} if ifname not in interfaces: interfaces[ifname] = {'ipv6': ipv6} else: interfaces[ifname].update({'ipv6': ipv6}) m = re.match(LINK_LOCAL_ADDRESS, line) if m: ip = m.group(1) ipv6.update({ip: {"prefix_length": 10}}) m = re.match(GLOBAL_ADDRESS, line) if m: ip, prefix = m.groups() ipv6.update({ip: {"prefix_length": int(prefix)}}) # Interface without ipv6 doesn't appears in show ipv6 interface return interfaces 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
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')