def ssh_device(device): try: guesser = SSHDetect(**device) best_match = guesser.autodetect() print(best_match) print(guesser.potential_matches) device['device_type'] = best_match net_connect = ConnectHandler(**device) host_ip = device['host'] # If the device matched is JUNIPER if best_match == 'juniper_junos': #Check if the device is MX or EX output = net_connect.send_command('show version |match model') model = output.split()[1] if model.__contains__("ex"): output = net_connect.send_command('show version | display json | no-more') output1 = net_connect.send_command('show virtual-chassis | display json | no-more') juniper_ex(output,output1,host_ip,model) if model.__contains__("mx"): output = net_connect.send_command('show version | display json | no-more') output1 = net_connect.send_command('show chassis hardware | display json | no-more') juniper_mx(output,output1,host_ip,model) except(AuthenticationException): print("Error connecting to device:", device['host']) except(NetMikoTimeoutException): print("SSH detect timeout for device:", device['host']) return
def access_device(ipaddress, username, password): now = datetime.datetime.now() print('') rprint('[red]Start time[red]', now) print('') rprint('[green]Checking connection to {}[green]'.format(ipaddress)) response = os.system('ping -c1 {}'.format(ipaddress)) if response == 0: rprint('[cyan]...DEVICE IS ACTIVE[cyan]') else: rprint('[red]...DEVICE IS DOWN [red]') remote_device = { 'device_type': 'autodetect', 'ip': ipaddress, 'username': username, 'password': password } try: netconnect = SSHDetect(**remote_device) match = netconnect.autodetect() rprint('...Checking device type..') rprint('Device type: {}'.format(match)) print('') remote_device['device_type'] = match return remote_device except (NetMikoTimeoutException, SSHException, AuthenticationException): rprint('[red]######CHECK DEVICE IP OR YOU PASSWORD######[red]')
def guess_netmiko_device_type(self, **kwargs): """Guess the device type of host, based on Netmiko.""" guessed_device_type = None remote_device = { "device_type": "autodetect", "host": kwargs.get("host"), "username": kwargs.get("username"), "password": kwargs.get("password"), "secret": kwargs.get("secret"), } try: logging.info("INFO guessing device type: %s", kwargs.get("host")) guesser = SSHDetect(**remote_device) guessed_device_type = guesser.autodetect() logging.info("INFO guessed device type: %s", guessed_device_type) except NetMikoAuthenticationException as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-login", message="ERROR {}".format(str(err))) except (NetMikoTimeoutException, SSHException) as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-connect", message="ERROR {}".format(str(err))) except Exception as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-general", message="ERROR {}".format(str(err))) logging.info("INFO device type is %s", guessed_device_type) # Get the platform map from the PLUGIN SETTINGS, Return the result of doing a check_netmiko_conversion return self.check_netmiko_conversion(guessed_device_type, platform_map=PLUGIN_SETTINGS.get("platform_map", {}))
def get_device_interfaces(ip_addr): """ Method to get interfaces of the device """ remote_device = { "device_type": "autodetect", "host": ip_addr, "username": "******", "password": "******", } guesser = SSHDetect(**remote_device) netmiko_guessed_os = guesser.autodetect() # get NAPALM driver name from MAPPER dict created above print( f"{ip_addr}: GET NAPALM DRIVER NAME FROM NETMIKO GUESSED OS PLATFORM") driver_name = NETMIKO_OS_TO_DRIVER_MAP.get(netmiko_guessed_os, None) if not driver_name: print( f"{ip_addr}: NETMIKO GUESSED OS PLATFORM DOES NOT MAP TO A NAPALM DRIVER" ) # if the OS type does not exist in the mapper dict, which means driver_name is None return None print(f"{ip_addr}: USING NAPALM DRIVER TO CONNECT TO THE DEVICE") driver = get_network_driver(driver_name) device = driver(ip_addr, "<<< YOUR REMOTE LOGIN USERNAME >>>", "<<< YOUR REMOTE LOGIN PASSWORD >>>") device.open() res = device.get_interfaces() return res
def _get_device_drivers(host, module): """Use netmiko autodetect to get netmiko and NAPALM drivers """ # find a credential that matches this host credentials = module.params['credentials'] logger = module.logger for cred in credentials: try: guesser = SSHDetect( device_type="autodetect", host=host, username=cred['credential']['username'], password=cred['credential']['password'], ) netmiko_driver = guesser.autodetect() except Exception as e: logger.error("Problem detecting device type via netmiko - %s" % e) continue try: napalm_driver = NETMIKO_NAPALM_DICT[netmiko_driver] except KeyError: logger.error("Detected device vendor not currently supported") return "", "", "" return netmiko_driver, napalm_driver, cred return "", "", ""
def device_access(ip_name): # Checking device reachability response = os.system('ping -c1 {}'.format(ip_name)) if response == 0: cprint('...DEVICE IS ACTIVE..', 'green', 'on_red') else: cprint('..DEVICE IS DOWN...', 'green', 'on_red') remote_device = { 'device_type': 'autodetect', 'ip': ip_name, 'username': '******', 'password': '******' } try: netconnect = SSHDetect(**remote_device) match = netconnect.autodetect() print('') cprint('...Checking device type..', 'yellow', 'on_red') cprint('Device type: {}'.format(match), 'yellow', 'on_red') print('') remote_device['device_type'] = match return remote_device except NetMikoTimeoutException: cprint('Device not reachable..', 'green', 'on_red') except AuthenticationException: cprint('Authentication Failure..', 'green', 'on_red') except SSHException: cprint('Make sure ssh is enable', 'green', 'on_red')
def guess_netmiko_device_type(self): """Guess the device type of host, based on Netmiko.""" guessed_device_type = None netmiko_optional_args = netmiko_args(self.optional_args) remote_device = { "device_type": "autodetect", "host": self.hostname, "username": self.username, "password": self.password, **netmiko_optional_args, } if self.secret: remote_device["secret"] = self.secret if self.port: remote_device["port"] = self.port if self.timeout: remote_device["timeout"] = self.timeout try: logger.info("INFO guessing device type: %s", self.hostname) guesser = SSHDetect(**remote_device) guessed_device_type = guesser.autodetect() logger.info("INFO guessed device type: %s", guessed_device_type) except NetMikoAuthenticationException as err: logger.error("ERROR %s", err) raise OnboardException(reason="fail-login", message=f"ERROR: {str(err)}") except (NetMikoTimeoutException, SSHException) as err: logger.error("ERROR: %s", str(err)) raise OnboardException(reason="fail-connect", message=f"ERROR: {str(err)}") except Exception as err: logger.error("ERROR: %s", str(err)) raise OnboardException(reason="fail-general", message=f"ERROR: {str(err)}") else: if guessed_device_type is None: logger.error( "ERROR: Could not detect device type with SSHDetect") raise OnboardException( reason="fail-general", message="ERROR: Could not detect device type with SSHDetect" ) return guessed_device_type
def Detect_device_type(host_to_connect): myrouter = { 'device_type': 'autodetect', 'host': host_to_connect, 'username': Username, 'password': Password, } connection = SSHDetect(**myrouter) best_match = connection.autodetect() if best_match == None: best_match = "cisco_ios" return best_match
def _detect(self, device): net_connect = { 'device_type': 'autodetect', 'host': device, 'username': self._username, 'password': self._password } if self._global_delay_factor: net_connect['global_delay_factor'] = self._global_delay_factor detecter = SSHDetect(**net_connect) device_type = detecter.autodetect() detecter.connection.disconnect() return device_type
def run_script(host_ip): remote_device = { "device_type": "autodetect", "host": host_ip, "username": uname, "password": passwd } try: guesser = SSHDetect(**remote_device) best_match = guesser.autodetect() print(best_match + " is the device_type for " + host_ip) except: print("Error connecting to " + host_ip) pass
def guess_device_type(remote_device): """Auto-detect device type""" try: guesser = SSHDetect(**remote_device) best_match = guesser.autodetect() except (NetMikoAuthenticationException): print( f"Failed to execute CLI on {remote_device['host']} due to incorrect credentials." ) return None except (NetMikoTimeoutException, SSHException): print( f"Failed to execute CLI on {remote_device['host']} due to timeout or SSH not enabled." ) return None except ValueError: print( f"Unsupported platform {remote_device['host']}, {remote_device['device_type']}." ) return None else: return best_match
def Conectar_Equipamento(ip, device_type='-', comando='\n'): try: dados_conexao = { "host": ip, "username": usuario, "password": senha, "device_type": device_type, "banner_timeout": 100, "timeout": 100 } if dados_conexao['device_type'] == '-': dados_conexao['device_type'] = 'autodetect' guesser = SSHDetect(**dados_conexao) best_match = guesser.autodetect() print('Equipamento {} é do tipo: {}'.format(dados_conexao['host'], best_match)) dados_conexao["device_type"] = best_match net_connect = Netmiko(**dados_conexao) prompt = net_connect.find_prompt() # if device_type=='huawei': # print(net_connect.disable_paging(command='screen-length 0 temporary')) info_equip = net_connect.send_command(comando).splitlines() return info_equip except (NetMikoAuthenticationException) as e: print('Falha ao conectar ao equipamento {}. {} '.format(ip, e)) # output = ['', '-'] except (NetMikoTimeoutException, Exception) as e: print('Falha ao conectar ao equipamento {}. {} '.format(ip, e)) # output = ['', '-'] # return None
def guess_netmiko_device_type(**kwargs): """Guess the device type of host, based on Netmiko.""" guessed_device_type = None remote_device = { "device_type": "autodetect", "host": kwargs.get("host"), "username": kwargs.get("username"), "password": kwargs.get("password"), "secret": kwargs.get("secret"), } try: logging.info("INFO guessing device type: %s", kwargs.get("host")) guesser = SSHDetect(**remote_device) guessed_device_type = guesser.autodetect() logging.info("INFO guessed device type: %s", guessed_device_type) except NetMikoAuthenticationException as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-login", message="ERROR {}".format(str(err))) except (NetMikoTimeoutException, SSHException) as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-connect", message="ERROR {}".format(str(err))) except Exception as err: logging.error("ERROR %s", err) raise OnboardException(reason="fail-general", message="ERROR {}".format(str(err))) logging.info("INFO device type is %s", guessed_device_type) return guessed_device_type
def guess_netmiko_device_type(self): """Guess the device type of host, based on Netmiko.""" guessed_device_type = None remote_device = { "device_type": "autodetect", "host": self.hostname, "username": self.username, "password": self.password, "secret": self.secret, } try: logger.info("INFO guessing device type: %s", self.hostname) guesser = SSHDetect(**remote_device) guessed_device_type = guesser.autodetect() logger.info("INFO guessed device type: %s", guessed_device_type) except NetMikoAuthenticationException as err: logger.error("ERROR %s", err) raise OnboardException(reason="fail-login", message=f"ERROR: {str(err)}") except (NetMikoTimeoutException, SSHException) as err: logger.error("ERROR: %s", str(err)) raise OnboardException(reason="fail-connect", message=f"ERROR: {str(err)}") except Exception as err: logger.error("ERROR: %s", str(err)) raise OnboardException(reason="fail-general", message=f"ERROR: {str(err)}") logger.info("INFO device type is: %s", guessed_device_type) return guessed_device_type
ip_name = [] remote_device = {'device_type': 'autodetect', 'ip': ip_name, 'username': '******', 'password': '******' } device = ['192.168.1.131', '192.168.1.132'] for i in device: remote_device['ip'] = i print(remote_device) netconnect = SSHDetect(**remote_device) match = netconnect.autodetect() remote_device['device_type'] = match if remote_device['device_type'] == 'arista_eos': netconnect=ConnectHandler(**remote_device) cname = netconnect.find_prompt() netconnect.enable() pingstat = netconnect.send_command('ping 192.168.1.1 repeat 1') arista = [] with open('test.txt', 'w') as fin: for i in pingstat: fin.write(i) with open('test.txt', 'r') as fout: for i in fout: arista.append(i)
word_list= [] for devices in devices_list: starting_time = time() print ("Connecting to device: " + devices) ip_address_of_device = devices remote_device = {"device_type":"autodetect", "host": devices, "username": username, "password": password } try: guesser = SSHDetect(**remote_device) device_type = guesser.autodetect() print("Device_type:", device_type) net_connect = ConnectHandler(**remote_device) except (AuthenticationException): print ('Authentication failure: ' + devices) continue except (NetMikoTimeoutException): print ('Timeout to device: ' + devices) continue except (EOFError): print ('End of file while attempting device ' + devices) continue except (SSHException): print ('SSH Issue. Are you sure SSH is enabled? ' + devices)
def liveresult(): inputitems = request.form.to_dict() devicename = inputitems['Devicename'] username = inputitems['Username'] password = inputitems['password'] action = inputitems['commands'] foutput = [] devicecount = len(inputitems['Devicename'].split(",")) hostnames = inputitems['Devicename'].split(",") for i in range (0,devicecount): hostname = hostnames[i] try: remote_device = {'device_type': 'autodetect','host': hostname,'username': username,'password': password} guesser = SSHDetect(**remote_device) vendor = guesser.autodetect() except: vendor = "NULL" if "cisco_asa" in vendor: remote_device['device_type'] = vendor net_connect = ConnectHandler(**remote_device) if action == "Check Version": output = net_connect.send_command("show version") foutput.append("===========================" '\n' + "Version Details for " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Check Inventory": output = net_connect.send_command("show inventory") foutput.append("===========================" '\n' + "inventory For " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Interface Status": output = net_connect.send_command("show ip") foutput.append("===========================" '\n' + "Interface status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "CDP Status": output = net_connect.send_command("sh cdp neighbors") foutput.append("===========================" '\n' + "Neighbor status For "+ hostname + ": " '\n'+ "==========================="'\n'+ 'CDP/LLDP not supported by ASA') elif "cisco" in vendor: remote_device['device_type'] = vendor net_connect = ConnectHandler(**remote_device) if action == "Check Version": output = net_connect.send_command("show version") foutput.append("===========================" '\n' + "Version Details for " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Check Inventory": output = net_connect.send_command("show inventory") foutput.append("===========================" '\n' + "inventory For " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Interface Status": output = net_connect.send_command("show interface status") foutput.append("===========================" '\n' + "Interface status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "CDP Status": output = net_connect.send_command("sh cdp neighbors") foutput.append("===========================" '\n' + "Neighbor status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif "junos" in vendor: remote_device['device_type'] = vendor net_connect = ConnectHandler(**remote_device) if action == "Check Version": output = net_connect.send_command("show version") foutput.append("===========================" '\n' + "Version Details for " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Check Inventory": output = net_connect.send_command("show chassis hardware detail") foutput.append("===========================" '\n' + "inventory For " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Interface Status": output = net_connect.send_command("show interfaces terse") foutput.append("===========================" '\n' + "Interface status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "CDP Status": output = net_connect.send_command("sh lldp neighbors") foutput.append("===========================" '\n' + "Neighbor status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif "linux" in vendor: remote_device['device_type'] = vendor net_connect = ConnectHandler(**remote_device) if action == "Check Version": output = net_connect.send_command("tmsh show sys version") foutput.append("===========================" '\n' + "Version Details for " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Check Inventory": output = net_connect.send_command("tmsh show sys hardware") foutput.append("===========================" '\n' + "inventory For " + hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "Interface Status": output = net_connect.send_command("tmsh show sys ip-address") foutput.append("===========================" '\n' + "Interface IP status For "+ hostname + ": " '\n'+ "==========================="'\n'+ output) elif action == "CDP Status": #output = net_connect.send_command("sh lldp neighbors") foutput.append("===========================" '\n' + "Neighbor status For "+ hostname + ": " '\n'+ "==========================="'\n'+ 'CDP/LLDP not supported by F5') else: foutput.append('\n'+"Details for " + hostname + ": " + "Login not possible to the device")
def execute_scan(scan_pk): devices = Device.objects.all() scan = Scan.objects.get(pk=scan_pk) dev_total = len(devices) dev_scanned = 0 for i, device in enumerate(devices): scan.status = str(dev_scanned) + '/' + str(dev_total) + ' devices' scan.save() remote_device = { 'host': device.ip, 'username': scan.username, 'password': scan.password, 'device_type': device.device_type, } try: if remote_device['device_type'] == 'autodetect': guesser = SSHDetect(**remote_device) remote_device['device_type'] = guesser.autodetect() connection = ConnectHandler(**remote_device) if remote_device['device_type'] == 'cisco_ios': device_info = parse_output( platform=remote_device['device_type'], command="show version", data=connection.send_command("show version"), )[0] device.device_type = remote_device['device_type'] device.hostname = device_info['hostname'] device.image = device_info['running_image'] device.os_version = device_info['version'] device.uptime = device_info['uptime'] device.serial = device_info['serial'][0] device.mac = device_info['mac'][0].lower().replace(':', '.') device.hardware = device_info['hardware'][0] device.last_seen = timezone.now() if not device.first_seen: device.first_seen = device.last_seen device.save() interface_info = parse_output( platform=remote_device['device_type'], command="show ip int brief", data=connection.send_command("show ip int brief"), ) for item in interface_info: if item['ipaddr'] != 'unassigned': try: host = Host.objects.get(pk=item['ipaddr']) host.delete() except Host.DoesNotExist: pass try: interface = Interface.objects.get( pk=item['ipaddr']) interface.name = item['intf'] interface.device = device except Interface.DoesNotExist: interface = Interface(ip=item['ipaddr'], name=item['intf'], device=device) interface.save() arp_info = parse_output( platform=remote_device['device_type'], command="show ip arp", data=connection.send_command("show ip arp"), ) for item in arp_info: try: interface = Interface.objects.get(pk=item['address']) interface.mac = item['mac'] interface.save() try: host = Host.objects.get(pk=item['address']) host.delete() except Host.DoesNotExist: pass except Interface.DoesNotExist: try: host = Host.objects.get(pk=item['address']) host.mac = item['mac'] host.vlan = item['interface'] host.last_seen = timezone.now() host.save() host.access_interface.add( Interface.objects.get(device=device, name=item['interface'])) host.scans_found.add(scan) except Host.DoesNotExist: host = Host(ip=item['address'], mac=item['mac'], vlan=item['interface']) host.first_seen = timezone.now() host.last_seen = timezone.now() host.save() host.access_interface.add( Interface.objects.get(device=device, name=item['interface'])) host.scans_found.add(scan) dev_scanned += 1 except: continue scan.finish_date = timezone.now() if dev_scanned == dev_total: scan.status = 'Completed' else: scan.status = 'Partial Failure' scan.username = scan.password = '' scan.save()
@author: wangkai """ from netmiko.ssh_autodetect import SSHDetect from netmiko.ssh_dispatcher import ConnectHandler import pandas as pd import re remote_device = { 'device_type': 'autodetect', 'host': '192.168.1.1', 'username': '******', 'password': '******', } guesser = SSHDetect(**remote_device) best_match = guesser.autodetect() print('Firmware Type:', best_match) remote_device['device_type'] = best_match connection = ConnectHandler(**remote_device) vlan_set = connection.send_command('show ip interface brief', use_textfsm=True) svi_list = [] for i in vlan_set: if 'Vlan' in i['intf']: svi_list.append(i['intf']) list1 = []