def autodetect(connect_kwargs): try: net_connect = SSHDetect(**connect_kwargs) print(net_connect.autodetect()) return net_connect.autodetect() except NetMikoTimeoutException: print('The IP address: {} did not respond, it might be unreachable'.format(connect_kwargs['host'])) except NetMikoAuthenticationException: print('Authentication failed for IP address: {}'.format(connect_kwargs['host']))
def auto_detect_device_type(cisco_device_info): # autodetect try: detect_device01 = SSHDetect(**cisco_device_info) except NetmikoTimeoutException: print(f"Network Connect Failure to Device {cisco_device_info['ip']}") except AuthenticationException: print(f"Authentication Failure to Device {cisco_device_info['ip']}") else: device_type = detect_device01.autodetect() return device_type
def find_device_type(hostname): base_device = { "device_type": "autodetect", "username": "******", "password": PASSWORD, } device = base_device.copy() device["host"] = hostname guesser = SSHDetect(**device) best_match = guesser.autodetect() return (hostname, best_match)
def detect_device(device, a_device): ''' Use the ssh deivce type detection to see what kind of device this is ''' try: guesser = SSHDetect(**a_device) best = guesser.autodetect() a_device['device_type'] = best except NetMikoTimeoutException: print("Connection failed to {} ".format(device['host'])) return None except Exception as e: print("Exception! {}".format(e)) return None return a_device
def try_connection(router, ip): ''' Funcion que utiliza Netmiko para conectarse a un equipo. Intenta detectar el tipo de equipo al que se va a conectar En caso de no poder averiguar el tipo de conexion SSH a realizar, se conectará bajo el modo de Cisco En caso de ser rechazada la conexion SSH, se intenta conectar a traves de Telnet En caso de conectar, retorna una conexion basada en Netmiko, de lo contrario retorna una lista vacia ''' conn=[] try: print('Detecting device type for ip '+ip) device = SSHDetect(**router).autodetect() if not device: device = 'cisco_ios' print('Trying SSH on ip {} of device type {}'.format(ip,device)) router['device_type'] = device conn = ConnectHandler(**router) except Exception as e: print(e) try: print('Trying Telnet on ip '+ip) router['device_type'] = 'cisco_ios_telnet' conn = ConnectHandler(**router) except Exception as e: print(e) print('Unable to connect to ip '+ip+'\n\n') return conn
def ssh_autodetect(request): """Create an SSH autodetect object. return (ssh_conn, real_device_type) """ device_under_test = request.config.getoption('test_device') test_devices = parse_yaml(PWD + "/etc/test_devices.yml") device = test_devices[device_under_test] device['verbose'] = False my_device_type = device.pop('device_type') device['device_type'] = 'autodetect' conn = SSHDetect(**device) return (conn, my_device_type)
def deviceconnector(i, q): # This while loop runs indefinitely and grabs IP addresses from the queue and processes them # Loop will be blocked and wait if "ip = q.get()" is empty while True: ip = q.get() with print_lock: print('Th{}/{}: Acquired IP: {}'.format(i + 1, threads, ip)) #Create an error log file errorfile = open( 'valkyrie output/valkyrie errors ' + str(date.today()) + '.txt', 'a') # device_dict is copied over to net_connect device_dict = { 'host': ip, 'username': username, 'password': password, 'secret': secret, 'device_type': 'autodetect', 'banner_timeout': 60, 'conn_timeout': 60 # Gather session output logs - TESTING ONLY # , # 'session_log': 'session_output.txt' } # device type autodetect based on netmiko try: auto_device_dict = SSHDetect(**device_dict) device_os = auto_device_dict.autodetect() # Validate device type returned (Testing only) # print('===== {} =====\n===== {} ====='.format(device_os, auto_device_dict.potential_matches)) # Update device_dict device_type from 'autodetect' to the detected OS if device_os is None: print('Th{}/{}: {} returned unsupported device_type of {}\n'. format(i + 1, threads, device_dict['host'], device_os)) device_dict['device_type'] = 'autodetect' else: device_dict['device_type'] = device_os # Connect to the device, and print out auth or timeout errors net_connect = Netmiko(**device_dict) print('Th{}/{}: Connecting to: {} ({})'.format( i + 1, threads, net_connect.host, net_connect.device_type)) except NetMikoTimeoutException: with print_lock: print('Th{}/{}: ERROR: Connection to {} timed-out. \n'.format( i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: Connection timed-out. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break except (NetMikoAuthenticationException, AuthenticationException): with print_lock: print( 'Th{}/{}: ERROR: Authentication failed for {}. Stopping thread. \n' .format(i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: Authentication failed. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break except NoValidConnectionsError: with print_lock: print( 'Th{}/{}: ERROR: No Connections available for device {}. \n' .format(i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: No Connections available. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break # Capture the output # TODO TextFSM to parse data # create two variables - one of hostname and the prompt level and another with just the hostname prompt = net_connect.find_prompt() hostname = prompt.rstrip('#>') print('Th{}/{}: Associated IP: {} with hostname: {}'.format( i + 1, threads, ip, hostname)) # TODO Write file to a optional, specified folder timenow = '{:%Y-%m-%d %H_%M_%S}'.format(datetime.now()) start = datetime.now() filename = (hostname + ' ' + ip + ' - valkyrie output {0}.txt') outputfile = open('valkyrie output/' + filename.format(timenow), 'w') print('Th{}/{}: Writing file name "{} {} - valkyrie output {}.txt"'. format(i + 1, threads, hostname, ip, format(timenow))) if device_os == 'cisco_ios': for cmd in commands: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_nxos': for cmd in commands_nexus: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_wlc': for cmd in commands_wlc: try: if re.match(r'\w', cmd): if cmd == 'show run-config': output = net_connect.send_command_timing( cmd.strip(), delay_factor=1, max_loops=1000) if 'Press Enter to continue' in output: output += net_connect.send_command_timing('\n') write_file(outputfile, prompt, cmd, output) else: output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_asa': for cmd in commands_asa: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) else: for cmd in commands_showtech: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) # Disconnect from device net_connect.disconnect() # Close the file outputfile.close() errorfile.close() # verify elapsed time per device end = datetime.now() print('Th{}/{}: Completed. Time elapsed: {}'.format( i + 1, threads, (end - start))) # Set the queue task as complete, thereby removing it from the queue indefinitely q.task_done()
#!/usr/bin/python from netmiko import Netmiko from netmiko import SSHDetect target = '11.11.11.171' user = '******' pwd = 'msfadmin' device = 'linux' device = { "device_type": "autodetect", "host": target, "username": user, "password": pwd } sshtarget = SSHDetect(**device) best_match = sshtarget.autodetect() print('Isso eh provavelmente:', best_match) print('Pontecial de:', str(sshtarget.potential_matches))
from netmiko import SSHDetect, ConnectHandler from getpass import getpass device = { 'device_type': 'autodetect', 'ip': 'x.x.x.x', 'username': '******', 'password': getpass(), } guesser = SSHDetect(**device) best_match = guesser.autodetect() print(best_match) print(guesser.potential_matches) device["device_type"] = best_match with ConnectHandler(**device) as connection: print(connection.find_prompt())
#!/usr/bin/env python from netmiko import SSHDetect, Netmiko from getpass import getpass device = { 'device_type': 'autodetect', 'host': 'cisco1.twb-tech.com', 'username': '******', 'password': getpass(), } guesser = SSHDetect(**device) best_match = guesser.autodetect() print(best_match) # Name of the best device_type to use further print(guesser.potential_matches) # Dictionary of the whole matching result device['device_type'] = best_match connection = Netmiko(**device) print(connection.find_prompt())
# Detect an unknown device types from pprint import pprint from netmiko import ConnectHandler, SSHDetect # Define a device device = { "device_type": "autodetect", # Notice autodetect "ip": "sandbox-iosxe-latest-1.cisco.com", "username": "******", "password": "******", "port": 22, "fast_cli": False, } # Define guessing variables best_match = SSHDetect(**device).autodetect() print("\nDevice Type Best Match:", best_match, end="\n\n") # Override autodetect value with the best match device["device_type"] = best_match # Create an SSH connection instance with ConnectHandler(**device) as net_connect: facts = net_connect.send_command(command_sting="show version", use_textfsm=True) pprint(facts) print("Done")
def guess_device(ip, port=None): #device_credentials = {"device_username": "******", # "device_password": "******", # "device_secret": "password" # for entering in (enable) exec mode on cisco device. # } device_credentials = { "device_username": current_app.config["DEVICE_USERNAME"], "device_password": current_app.config["DEVICE_PASSWORD"], "device_secret": current_app.config["DEVICE_SECRET"] } # (STANDARD FAILURE DICTIONARY) AND SET VALUES FOR THIS OPERATION ERROR error_dictionary = { "STATUS": "Failure", "ERROR": "4", "TYPE": {}, "MESSAGE": {} } try: if port is None: port = 22 guesser = SSHDetect(device_type="autodetect", ip=ip, username=device_credentials["device_username"], password=device_credentials["device_password"], secret=device_credentials["device_secret"], port=port) best_match = guesser.autodetect() print("OUTPUT _INSIDE - guess_device function") print("OUTPUT - best_match is: ", best_match) # Name of the best device_type to use further print("OUTPUT - Dictionary of the whole matching results: ", guesser. potential_matches) # Dictionary of the whole matching result return best_match except AuthenticationException as e: error_dictionary["STATUS"] = "Failure" error_dictionary["TYPE"] = "AuthenticationException" error_dictionary["MESSAGE"] = str(e) # SEND ERROR MESSAGE TO CLIENT return error_dictionary except NetMikoTimeoutException as e: error_dictionary["STATUS"] = "Failure" error_dictionary["TYPE"] = "NetMikoTimeoutException" error_dictionary["MESSAGE"] = str(e) # SEND ERROR MESSAGE TO CLIENT return error_dictionary except SSHException as e: error_dictionary["STATUS"] = "Failure" error_dictionary["TYPE"] = "SSH_exception" if "Error reading SSH protocol banner" in str(e): error_dictionary[ "MESSAGE"] = "Error while connecting to device. Check port and connection type." else: error_dictionary["MESSAGE"] = str(e) # SEND ERROR MESSAGE TO CLIENT return error_dictionary except EOFError as e: error_dictionary["STATUS"] = "Failure" error_dictionary["TYPE"] = "EOFError" error_dictionary["MESSAGE"] = str(e) # SEND ERROR MESSAGE TO CLIENT return error_dictionary except Exception as unknown_error: error_dictionary["STATUS"] = "Failure" error_dictionary["TYPE"] = "unknown error" error_dictionary["MESSAGE"] = str(unknown_error) # SEND ERROR MESSAGE TO CLIENT return error_dictionary
def get_vendor(self): if self.device_data["device_type"] == "autodetect": message.info(f"Finding the vendor for the host: {self.device}") self.vendor = SSHDetect(**self.device_data).autodetect() message.success(f"Identified {self.device} as {self.vendor}") self.device_data["device_type"] = self.vendor
def sshLogin(hostName, userName, timeNow, passWord, hostName2, userName2, password2): # make a struct that include the host's information to auto ssh login deviceType = 'autodetect' device = { 'device_type': deviceType, #'device_type':'huawei_vrpv8', 'host': hostName, 'username': userName, 'password': passWord } # get the whitelist-profile name and then splice them into the final command print("\n--------------------------------------------------------") profileName = 'display sta-whitelist-profile name ' + input( "请输入whitelist-profile name: ") print("--------------------------------------------------------\n") #profileName = 'display sta-whitelist-profile name staff-devp' print("\n--------------------------------------------------------") print("正在尝试连接第一台主机,请稍候……") print("--------------------------------------------------------\n") guesser = SSHDetect(**device) deviceType = guesser.autodetect() with open('debug.log', 'a+', encoding='utf-8') as f: f.write( '\n\n\n--------------------------------------------------------\n') f.write('--------------------------------------------------------\n') f.write(timeNow) f.write(',') f.write(hostName) f.write(',') f.write(userName) f.write(',') f.write(deviceType) f.write(',') f.write(str(guesser.potential_matches)) f.write('\n--------------------------------------------------------\n') print(deviceType) # Name of the best device_type to use further print(guesser.potential_matches) # Dictionary of the whole matching result # using ssh to login the target host net_connect = ConnectHandler(**device) net_connect.send_command_timing('n') print("\n--------------------------------------------------------") print("第一台主机连接成功,正在尝试连接第二台主机,请稍候……") print("--------------------------------------------------------\n") # set the commands that need to be executed after login stelnetHost2 = 'stelnet ' + hostName2 #config_commands1 = ['system', stelnetHost2,userName2] # excute the commands #output1 = net_connect.send_config_set(config_commands1) #print(output1) allOutput = '\n' output = net_connect.send_command_timing('system-view') print(output) allOutput = allOutput + '\n' + output output = net_connect.send_command_timing(stelnetHost2) print(output) allOutput = allOutput + '\n' + output net_connect.send_command_timing('y') net_connect.send_command_timing('n') output = net_connect.send_command_timing(userName2) print(output) allOutput = '\n' allOutput = allOutput + '\n' + output output = net_connect.send_command_timing(passWord2) print(output) allOutput = allOutput + '\n' + output output = net_connect.send_command_timing('screen-length 0 temporary') print(output) allOutput = allOutput + '\n' + output output = net_connect.send_command_timing('system-view') print(output) allOutput = allOutput + '\n' + output output = net_connect.send_command_timing('wlan') print(output) allOutput = allOutput + '\n' + output output = net_connect.send_command_timing(profileName) print(output) allOutput = allOutput + '\n' + output ''' i = 0 while i < 3 : output = net_connect.send_command_timing('') i = i+1 print(output) allOutput = allOutput + '\n' + output ''' # print all the process and Results #output = output1 + '\n' + output2 + '\n' + output4 + '\n' + output5 + '\n' + output6 # log all the process and Results with open('debug.log', 'a+', encoding='utf-8') as f: f.write('\n--------------------------------------------------------\n') f.write(allOutput) f.write('\n--------------------------------------------------------\n') f.write('--------------------------------------------------------\n') # display the dividing line to split display area print("\n--------------------------------------------------------") print('log日志写入完成,文件位于根目录下') print("--------------------------------------------------------\n") makeDir('./cache/') # write all the process and Results into cache file with open('./cache/' + hostName2 + '-' + timeNow, 'w', encoding='utf-8') as f: f.write(allOutput) # display the dividing line to split display area print("\n--------------------------------------------------------") print('cache写入完成,文件位于cache目录下') print("--------------------------------------------------------\n") # disconnect with host net_connect.disconnect()
# Iterate through the devices that were passed and attempt to gather information. for device in ipaddress: remote_device = {'device_type': 'autodetect', 'host': device, 'username': username, 'password': password} print ("------------------------------------------------------------") print ("Performing a health check on "+device) # Try to detect the type of deevice try: guesser = SSHDetect(**remote_device,timeout=10) except (NetMikoAuthenticationException, NetMikoTimeoutException) as e: print("Error connecting to device: "+str(e)) continue best_match = guesser.autodetect() print("This device is detected to be model type: " + best_match) if best_match not in ['cisco_ios', 'cisco_nxos', 'cisco_xr']: print("ERROR: " + best_match + " is not currently supported in this revision") continue else: remote_device['device_type'] = best_match
def send_commands(dic_command, dic_device): """ Function, witch send commands to devices and get output :param command: Command for send :param dic_device: Dictionary with parameters device for connection :return: Dictionary {device: output} """ if verbose_flag: print('Connection to device: {}'.format(dic_device['ip'])) # An attempt to understand what kind of device we are connecting to # For the first attempt we will use Netmiko try: guesser = SSHDetect(timeout=10, **dic_device) best_match = guesser.autodetect() except: if verbose_flag: print( '\n', 'Something went wrong.' ' Username or password for device {} are incorrect, or SSH is down on the device' .format(dic_device['ip'])) return ({ 'ip': dic_device['ip'], 'output': None, 'device_type': None }) if best_match is not None: dic_device[ 'device_type'] = best_match # It works fine for Cisco IOS devises else: # All have to do yourself :( . We are trying to determine the type of device independently. try: # We are using paramiko to connect to device client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=dic_device['ip'], username=dic_device['username'], password=dic_device['password'], look_for_keys=False, allow_agent=False) with client.invoke_shell() as ssh: result = ssh.recv(100).decode('utf-8') if '(Cisco Controller)' in result: # If we have connection to Cisco WLC, then we get typically WLC's welcome message dic_device['device_type'] = 'cisco_wlc' else: # Otherwise, we have a connection to Cisco SMB dic_device['device_type'] = 'cisco_s300' except: if verbose_flag: print( '\n', 'Something went wrong.' ' Username or password for device {} are incorrect, or SSH is down on the device' .format(dic_device['ip'])) return ({ 'ip': dic_device['ip'], 'output': None, 'device_type': None }) # To avoid "%AAA-I-DISCONNECT: User CLI session for user <username> over ssh , source <ip> # destination <ip> TERMINATED. The Telnet/SSH session may still be connected." # We need to waiting time.sleep(3) # Connecting to device, sending command and getting output try: command_result = {} with ConnectHandler(timeout=10, **dic_device) as ssh: if ssh.check_config_mode is False: ssh.enable() # Select a list of commands based on the type of device command_list = dic_command[dic_device['device_type']] # Running selected commands for device for command in command_list: result = ssh.send_command(command) result = result.strip() command_result.update({command: result}) # Determine the host name for 'cisco_ios' and 'cisco_s300' devices find_hostname = 'WLC' if dic_device['device_type'] is 'cisco_ios' or dic_device[ 'device_type'] is 'cisco_s300': find_hostname = ssh.find_prompt() if '>' in find_hostname: find_hostname = find_hostname.replace('>', '') elif '#' in find_hostname: find_hostname = find_hostname.replace('#', '') find_hostname = find_hostname.strip() ssh.disconnect() return ({ 'ip': dic_device['ip'], 'output': command_result, 'hostname': find_hostname, 'device_type': dic_device['device_type'] }) except: if verbose_flag: print( '\n', 'Something went wrong.' ' Username or password for device {} are incorrect, or SSH is down on the device.' .format(dic_device['ip'])) print( 'Or, you are trying to connect to an unsupported device and the SSH session cannot work correctly' ) return ({ 'ip': dic_device['ip'], 'output': None, 'device_type': dic_device['device_type'] })
with open('Cisco_commands') as commandsciscofile: Cisco_commands_file = commandsciscofile.read().splitlines() with open('devices_all') as f: devices_list = f.read().splitlines() for host_ip in devices_list: print('connecting to device ' + host_ip) ipaddress = host_ip device = { 'device_type': 'autodetect', 'host': ipaddress, 'username': username, 'password': password, } detect_device = SSHDetect(**device) device_type = detect_device.autodetect() print(device_type) if device_type == 'juniper_junos': print('device is ' + 'juniper box') network_device = { 'device_type': device_type, 'ip': ipaddress, 'username': username, 'password': password } net_connect = ConnectHandler(**network_device) output = net_connect.send_config_set(juniper_commands_file) print(output) elif device_type == None: print('device is ' + 'cisco box ')
- pulls the hostname, username, and password from the .csv file - builds a dictionary with this informaiton - creates an SSH session and stores it as ssh_session variable - finds the hostname and replaces the # sign from the prompt - prints out to the console a bunch of pretty formatting to highlight what device we're currently iterating through. - grabs the output of a show cdp neighbor detail, only including relevant information ''' hostname = row['hostname'] username = row['username'] password = row['password'] enable_secret = row['enable_secret'] target_device = {'device_type': 'autodetect', 'ip': hostname, 'username': username, 'password': password, 'secret': enable_secret, 'verbose': False} ssh_session = ConnectHandler(**target_device) detected_type = SSHDetect(**target_device).autodetect() ssh_session.enable() hostname = ssh_session.find_prompt().replace("#", "") # strips out the # sign from the Cisco prompt print(hostname + ' is a ' + detected_type + '\n') if detected_type == 'cisco_ios': ''' call platform specific module handling individual task ''' cisco_ios_show_crypto.show_crypto(ssh_session, hostname) ''' elif detected_type == 'cisco_asa': ''' ''' MAIN APP - FINISH '''