def connect_to(thisrouter, thisusername, thispassword): device = { "host": thisrouter["device-IP"], "username": thisusername, "password": thispassword, "device_type": "cisco_ios", } protocol = "SSH" thisconnection = False print("Connecting to", thisrouter['device-ID']) try: print("Trying SSH ...") print() thisconnection = netmiko.Netmiko(**device) except: #(SSHException,NetMikoTimeoutException,NoValidConnectionsError) : logger.warning("Failed to connect over %s to %s", protocol, thisrouter['device-ID']) device['device_type'] = "cisco_ios_telnet" protocol = "Telnet" try: print("Trying Telnet ...") print() thisconnection = netmiko.Netmiko(**device) except: #(NetMikoTimeoutException,NoValidConnectionsError) : logger.warning("Failed to connect over %s to %s", protocol, thisrouter['device-ID']) finally: if thisconnection != False: print("Success") print() logger.info("Successfully connected to %s over %s", thisrouter['device-ID'], protocol) return (thisconnection)
def ssh_sure_shell_login(device): # snmp可达性 snmp_reachable = snmp_sure_reachable(device.get('ip'), device.get('snmp_ro_community')) # 保存SNMP可达性和SSH可达性到数据库 def save_sql(verdict): d = DeviceReachable(device_id=device.get('id'), ssh_reachable=verdict, snmp_reachable=snmp_reachable) d.save() # 判断华为或华三设备的SSH可达性 if device.get('type_name') in device_types: try: # 建立SSH连接 huawei_ssh = netmiko.Netmiko(device_type='huawei_ssh', ip=device.get('ip'), username=device.get('username'), password=device.get('password')) # 启用enable进入特权模式 huawei_ssh.config_mode() # 找到当前所在层级并赋值给ssh_reachable ssh_reachable = huawei_ssh.find_prompt() # 关闭连接 huawei_ssh.disconnect() # 正则匹配,确认是否进入用户模式 if re.search(']', ssh_reachable): save_sql('True') else: save_sql('False') except Exception as a: print(a) save_sql('False') else: try: # 建立SSH连接 cisco_ssh = netmiko.Netmiko(device_type='cisco_asa_ssh', ip=device.get('ip'), username=device.get('username'), password=device.get('password'), secret=device.get('enable_pwd')) # 启用config_mode进入配置模式 cisco_ssh.enable() # 找到当前所在层级并赋值给ssh_reachable ssh_reachable = cisco_ssh.find_prompt() # 关闭连接 cisco_ssh.disconnect() # 正则匹配,确认是否进入配置模式 if re.search('#', ssh_reachable): save_sql('True') else: save_sql('False') except Exception as a: save_sql('False')
def ssh_netmiko(vid, device_ip): vlanid = str(vid) # 使用VLANID产生子网 network_sub = "172.16." + vlanid + "." # 下面是DHCP的具体CLI命令的列表 dhcp_pool_command = [ "ip dhcp pool Vlan" + vlanid, "network " + network_sub + "0 /24", "default-router " + network_sub + "1", "dns-server 8.8.8.8", "exit", "ip dhcp excluded-address " + network_sub + "1 " + network_sub + "99", "ip dhcp excluded-address " + network_sub + "101 " + network_sub + "254", ] # 建立SSH连接 cisco_ssh = netmiko.Netmiko(device_type='cisco_ios', ip=device_ip, username=username, password=password, secret=enable_pwd) # 启用enable进入特权模式 cisco_ssh.enable() # 执行命令前会默认执行config term进入全局配置模式,netmiko收到设备的回应提示符后,会自动执行下一条命令 result = cisco_ssh.send_config_set(dhcp_pool_command) print(result) print('=' * 100) print("DHCP Service for CentOS_" + vlanid + " is all ready") cisco_ssh.disconnect()
def _open_telnet_and_login_to_user_EXEC(self): logging.info( '_open_telnet_and_login_to_user_EXEC: trying to open telnet connection' ) # if password was not provided pick default password, else login with provided password if self.user_password == "": # trying to login using default passwords for password in default_password_list: try: logging.info( '_open_telnet_and_login_to_user_EXEC: password:'******'', port=self.port, device_type='cisco_ios_telnet', timeout=20, session_timeout=10, auth_timeout=15) self.user_password = password break except netmiko.NetMikoAuthenticationException: # if login failed, catch that exception, log that, and start next iteration logging.info( '_open_telnet_and_login_to_user_EXEC: password failed') continue # if loop was exited not by "break", which means that all login attempts failed, raise that else: raise netmiko.NetMikoAuthenticationException( "Login to user EXEC failed: {}".format(self.name)) else: self.telnet_netmiko = netmiko.Netmiko( host=self.address, password=self.user_password, secret=self.priv_password, port=self.port, device_type='cisco_ios_telnet', timeout=20, session_timeout=10, auth_timeout=15) logging.info( '_open_telnet_and_login_to_user_EXEC: opened telnet connection')
def send_show(device, command): try: with netmiko.Netmiko(**device) as ssh: ssh.enable() result = ssh.send_command(command) return result except netmiko.NetmikoTimeoutException as error: print(f"Failed to connect to {device['host']}") except paramiko.ssh_exception.AuthenticationException: print(f"Authentication error on {device['host']}")
def connect_to_dev(dev_dict): # Safely attempt to connect to a device and gracefully exit. try: connection_object = netmiko.Netmiko(**dev_dict) except Exception as e: print(f"ERROR. Could not establish connection to {dev_dict['host']}!\nException: {e}\nAborting Program!") exit() return connection_object
def send_cmd_with_prompt(device, command, *, wait_for, confirmation): with netmiko.Netmiko(**device) as ssh: ssh.enable() result = ssh.send_command_timing(command, strip_prompt=False, strip_command=False) if wait_for in result: result += ssh.send_command_timing(confirmation, strip_prompt=False, strip_command=False) return result
def blocking_task_connect(device: dict, uid: int): """Blocking function responsible for starting the netmiko session""" global found try: dev = netmiko.Netmiko(**device) print( f'{green}[*] - Successfully connected to host {device["host"]} on worker {uid}{reset}' ) if dev.check_enable_mode(): print( f'{green}[!] - We are currently in level 15 privilege mode! No password?!{reset}' ) return secret = None while not found: if dev.check_enable_mode(): print( f'{green}[!] - Password "{secret}" worked as the secret password!{reset}' ) found = True break dev.send_command('enable', expect_string='word', delay_factor=2) secret = work_queue.get_nowait() print(f'{bold}[*] - Attempting "enable" password {secret}{reset}') output = dev.send_command_timing(secret, strip_prompt=False) if '#' in output: continue secret = work_queue.get_nowait() print(f'{bold}[*] - Attempting "enable" password {secret}{reset}') output = dev.send_command_timing(secret, strip_prompt=False) if '#' in output: continue secret = work_queue.get_nowait() print(f'{bold}[*] - Attempting "enable" password {secret}{reset}') output = dev.send_command_timing(secret, strip_prompt=False) if '#' in output: continue print(f'{bold}[*] - Closing worker {uid}!{reset}') except asyncio.queues.QueueEmpty: pass except netmiko.ssh_exception: pass except netmiko.NetmikoAuthenticationException: print( f'{red}[x] - SSH Authentication Error using --> {device["username"]} and {device["password"]}' ) except netmiko.NetMikoTimeoutException: print(f'{red}[x] - SSH Connection to {device["host"]} timed out')
def send_cmd_with_prompt_expect(device, command, *, wait_for, confirmation): with netmiko.Netmiko(**device) as ssh: ssh.enable() result = ssh.send_command(command, expect_string=wait_for, strip_prompt=False, strip_command=False) result += ssh.send_command(confirmation, expect_string="#", strip_prompt=False, strip_command=False) return result
def send_show(device, command): host = device["host"] logging.info(f">>> Connecting to {host}") try: with netmiko.Netmiko(**device) as ssh: ssh.enable() output = ssh.send_command(command) return {host: output} except netmiko.NetmikoTimeoutException as error: logging.info(f"Failed to connect to {host}") except paramiko.ssh_exception.AuthenticationException: logging.info(f"Authentication error on {host}")
def send_show_command(device, show): host = device["host"] logging.info(f">>> Connecting to {host}") try: with netmiko.Netmiko(**device) as ssh: ssh.enable() output = ssh.send_command(show) logging.debug(f"\n{output}\n") logging.info(f"<<< Received output from {host}") return output except netmiko.NetmikoTimeoutException as error: logging.info(f"Failed to connect to {host}") except paramiko.ssh_exception.AuthenticationException: logging.info(f"Authentication error on {host}")
def send_show(device, commands): result = {} if type(commands) == str: commands = [commands] try: with netmiko.Netmiko(**device) as ssh: ssh.enable() for cmd in commands: output = ssh.send_command(cmd) result[cmd] = output return result except netmiko.NetmikoTimeoutException as error: print(f"Failed to connect to {device['host']}") except paramiko.ssh_exception.AuthenticationException: print(f"Authentication error on {device['host']}")
def send_cmd_with_prompt(device, command, *, wait_for, confirmation): if type(wait_for) == str: wait_for = [wait_for] if type(confirmation) == str: confirmation = [confirmation] with netmiko.Netmiko(**device) as ssh: ssh.enable() result = ssh.send_command_timing( command, strip_prompt=False, strip_command=False ) for wait, confirm in zip(wait_for, confirmation): if wait in result: result += ssh.send_command_timing( confirm, strip_prompt=False, strip_command=False ) return result
def send_and_parse_show_commands(device, commands, templates_path=None): if "NET_TEXTFSM" not in os.environ: if not templates_path: raise ValueError( "For the function to work, you must either specify an" "environment variable NET_TEXTFSM or specify a templates_path") os.environ["NET_TEXTFSM"] = templates_path result = {} if type(commands) == str: commands = [commands] with netmiko.Netmiko(**device) as ssh: ssh.enable() for cmd in commands: output = ssh.send_command(cmd, use_textfsm=True) result[cmd] = output return result
def run(self): """ Connect to host in list and gather MAC addresses information and store in self.hosts """ # Init local variables interface_mac = {} interface_status = {} # Loop to gather hosts information hosts = self.host_list['hosts'] for host in hosts: self._add_host(host) try: # Connecto to host device_type = hosts[host] host_connect = netmiko.Netmiko(host=host, username=username, password=password, device_type=device_type) logger.info("Connect to host {}".format(host)) # Send command interface_mac = host_connect.send_command( "show mac address-table", use_genie=True) logger.debug( "Output of the show mac address-table \n{}".format( json.dumps(interface_mac, indent=4, skipkeys=False, ensure_ascii=True))) interface_status = host_connect.send_command( "show interfaces status", use_genie=True) logger.debug("Output of the show interface_status \n{}".format( json.dumps(interface_status, indent=4))) logger.info("Gather host {} information".format(host)) except Exception as e: logger.warning('Failed to connect to host {}: {}'.format( host, str(e))) self._add_interface_mac(host, interface_mac) self._add_interface_status(host, interface_status) return (self.hosts)
def send_show(device, show_commands): host = device["host"] if type(show_commands) == str: show_commands = [show_commands] cmd_dict = {} logging.info(f">>> Connecting to {host}") try: with netmiko.Netmiko(**device) as ssh: ssh.enable() for cmd in show_commands: output = ssh.send_command(cmd) cmd_dict[cmd] = output logging.info(f"<<< Received output from {host}") return {host: cmd_dict} except netmiko.NetmikoTimeoutException as error: logging.info(f"Failed to connect to {host}") except paramiko.ssh_exception.AuthenticationException: logging.info(f"Authentication error on {host}")
import netmiko from netmiko import ConnectHandler from netmiko import BaseConnection from .credentails import password1, username1 cisco1 = { "ip": "10.223.2.100", "username": username1, "password": password1, "device_type": "cisco_wlc", 'global_delay_factor': 4, 'banner_timeout': 15 } net_connect = netmiko.Netmiko(**cisco1) # print(net_connect.find_prompt()) # output = net_connect.send_command("show ip int brief") # print(output) # output = net_connect.send_command("show logging") # print(output) # net_connect = BaseConnection(**cisco1).special_login_handler(delay_factor=5) # net_connect.special_login_handler(delay_factor=5) print(net_connect.find_prompt()) net_connect.disconnect() # output = net_connect.send_command("show ip int brief") # print(output) # output = net_connect.send_command("show logging") # print(output)
DescLo = input("Enter description for loopback:") IpLo = input("Enter ip for loopback:") MaskLo = input('Enter netmask for loopback:') loopback = { "int_name": "loopback{}".format(IntLo), "description": DescLo, "ip": IpLo, "netmask": MaskLo } interface_config = [ "interface {}".format(loopback["int_name"]), "description {}".format(loopback["description"]), "ip address {} {}".format(loopback["ip"], loopback["netmask"]), "no shutdown" ] print("Attempting to connect...") conn = netmiko.Netmiko(**router) print("-" * 30 + "\nConnection to router has been made!\n" + "-" * 30) output = conn.send_config_set(interface_config) print(output) print("backing up running config") backupconfig = conn.send_config_set('do show run') CONFIG_FILE = open("BackupConfig.txt", "a") CONFIG_FILE.write(backupconfig) CONFIG_FILE.close() print('file saved to running directory') conn.disconnect()
#print(wb.get_sheet_names()) #print(wb_sheet) row = 2 while row <= wb_sheet.max_row: device_dict[wb_sheet[('a' + str(row))].value] = [ wb_sheet[('b' + str(row))].value, wb_sheet[('c' + str(row))].value, wb_sheet[('d' + str(row))].value, wb_sheet[("e" + str(row))].value ] row += 1 # print(device_dict) for device_name, device_list in device_dict.items(): print("*" * 35) print("读取设备{},IP地址{}:".format(device_name, device_list[0]), '\n') connection = netmiko.Netmiko(ip=device_list[0], username=device_list[1], password=device_list[2], secret=device_list[3], device_type='cisco_ios') #进入enable模式 connection.enable() print("-" * 35) print("设备{}读取完成,正在备份配置。".format(device_name), '\n') file_run = connection.send_command('show run') #新建文件用来存储配置 file_config = open( "/home/wen/python/IOS/" + device_name + "_" + time.strftime("%Y-%m-%d %H:%M", time.localtime()) + ".txt", 'w') #依次把配置文件写入文本文件中 for each_bak in file_run: file_config.write(each_bak) print("-" * 35)
"wlc": "show interface summary" } # Set command print( f"\n\n== Setting command to execute for device type {dev_info['device_type']}" ) if dev_info['device_type'] == "cisco_asa": print(f"\tSetting ASA command {commands['asa']}") command = commands['asa'] elif dev_info['device_type'] == "cisco_wlc": print(f"\tSetting WLC command {commands['wlc']}") command = commands['wlc'] elif dev_info['device_type'] == "cisco_ios": print(f"\tSetting IOS command {commands['ios']}") command = commands['ios'] print(f"\n\n== Establishing connection to device {dev_info['host']}") net_connect = netmiko.Netmiko(**dev_info) print(f"\n== Connection Result: \n{net_connect}") print(f"\n== Display the device prompt:") print(net_connect.find_prompt()) print(f"\n== Output result of command <{command}>") output = net_connect.send_command(command) print(output) print(f"\n== Disconnect from device {dev_info['host']}") net_connect.disconnect() print(f"\n== Disconnected\n\n")
def send_show(device, command): with netmiko.Netmiko(**device) as ssh: ssh.enable() output = ssh.send_command(command) return output
def ssh_single_cmd(device): # 保存md5到数据库,保存文件到本地 def save_config(): config_filename = device.get('device_name') + '_' + datetime.now( ).strftime('%Y-%m-%d-%H-%M') + '_' + md5_value + '.txt' # 保存配置文件 with open(configdir + config_filename, 'w') as f: f.write(run_config) # 写入配置文件的md5到数据库,用来比较配置是否有更改 d = Deviceconfig(device_id=device.get('id'), hash=md5_value, config_filename=config_filename) d.save() # ASA配置备份 if device.get('type_name') == 'ASA Firewall': # 建立SSH连接 cisco_ssh = netmiko.Netmiko(device_type='cisco_asa_ssh', ip=device.get('ip'), username=device.get('username'), password=device.get('password'), secret=device.get('enable_pwd')) # 启用enable进入特权模式 cisco_ssh.enable() # 执行命令 result = cisco_ssh.send_config_set([asa_cmd]) # 关闭连接 cisco_ssh.disconnect() # 返回结果是列表,每一行字符串都是单独的元素 list_run_config = result.split('\n') # 初始下标 location = 0 host_location = 0 # 用来找到hostname出现的位置,可以用global变量代替 for i in list_run_config: if re.match('hostname .*', i): host_location = location # 定位hostname所在位置 else: location += 1 # 截取hostname开始往后的部分 list_run_config = list_run_config[host_location:-3] # 还原配置 join() 将序列使用指定字符串连接生成新的字符串 run_config = '\n'.join(list_run_config) # 指定hash算法 m = hashlib.md5() # 传入需要hash的内容 m.update(run_config.encode('utf-8')) # 计算hash值 md5_value = m.hexdigest() # 检查数据库中md5是否存在 try: print('Search index ...') last_config_backup = Deviceconfig.objects.filter( device=device.get('id')).order_by('-id')[0] if last_config_backup.hash == md5_value: # 如果本次配置的MD5值,与上一次备份配置的MD5值相同!略过此次操作 print('The index already exists', device.get('ip')) else: print('Create index ...', device.get('ip')) save_config() except IndexError as a: print('Create index ...', device.get('ip')) save_config() # 华为和华三配置备份 elif device.get('type_name') in device_types: # 建立SSH连接 huawei_ssh = netmiko.Netmiko(device_type='huawei_ssh', ip=device.get('ip'), username=device.get('username'), password=device.get('password'), secret=device.get('enable_pwd')) # 启用enable进入特权模式 huawei_ssh.config_mode() # 执行命令 result = huawei_ssh.send_config_set([huawei_cmd]) # 关闭连接 huawei_ssh.disconnect() # 返回结果是列表,每一行字符串都是单独的元素 list_run_config = result.split('\n') # 初始下标 location = 0 host_location = 0 # 用来找到hostname出现的位置,可以用global变量代替 for i in list_run_config: if re.match('sysname .*', i): host_location = location # 定位hostname所在位置 else: location += 1 # 截取hostname开始往后的部分 list_run_config = list_run_config[host_location:-2] # 还原配置 join() 将序列使用指定字符串连接生成新的字符串 run_config = '\n'.join(list_run_config) # 指定hash算法 m = hashlib.md5() # 传入需要hash的内容 m.update(run_config.encode('utf-8')) # 计算hash值 md5_value = m.hexdigest() # 检查数据库中md5是否存在 try: print('Search index ...') last_config_backup = Deviceconfig.objects.filter( device=device.get('id')).order_by('-id')[0] if last_config_backup.hash == md5_value: # 如果本次配置的MD5值,与上一次备份配置的MD5值相同!略过此次操作 print('The index already exists', device.get('ip')) else: print('Create index ...', device.get('ip')) save_config() except IndexError as a: print('Create index ...', device.get('ip')) save_config() # 其他思科设备配置备份 else: # 建立SSH连接 cisco_ssh = netmiko.Netmiko(device_type='cisco_ios', ip=device.get('ip'), username=device.get('username'), password=device.get('password'), secret=device.get('enable_pwd')) # 启用enable进入特权模式 cisco_ssh.enable() # 执行命令 result = cisco_ssh.send_config_set([ios_cmd]) # 关闭连接 cisco_ssh.disconnect() # 返回结果是列表,每一行字符串都是单独的元素 list_run_config = result.split('\n') # 初始下标 location = 0 host_location = 0 # 用来找到hostname出现的位置,可以用global变量代替 for i in list_run_config: if re.match('hostname .*', i): host_location = location # 定位hostname所在位置 else: location += 1 # 截取hostname开始往后的部分 list_run_config = list_run_config[host_location:-2] # 还原配置 join() 将序列使用指定字符串连接生成新的字符串 run_config = '\n'.join(list_run_config) # 指定hash算法 m = hashlib.md5() # 传入需要hash的内容 m.update(run_config.encode('utf-8')) # 计算hash值 md5_value = m.hexdigest() # 检查数据库中md5是否存在 try: print('Search index ...') last_config_backup = Deviceconfig.objects.filter( device=device.get('id')).order_by('-id')[0] if last_config_backup.hash == md5_value: # 如果本次配置的MD5值,与上一次备份配置的MD5值相同!略过此次操作 print('The index already exists', device.get('ip')) else: print('Create index ...', device.get('ip')) save_config() except IndexError as a: print('Create index ...', device.get('ip')) save_config()