1

我在“devices_list”中有 cisoc_ios 路由器和 fortinet 防火墙和 HP 交换机,但是当我运行此代码并遇到 fortinet 防火墙时,它不会给出错误,因为它不是 cisco_ios 并尝试登录。登录后它给出的错误为它无法进入配置模式(显然)。因此,我需要改进下面的代码,以便在 fortinet 或 hp 设备出现而不是尝试登录时代码会引发错误,并且它会继续运行,直到尝试了所有设备。

    from getpass import getpass
    from netmiko import ConnectHandler
    from netmiko.ssh_exception import NetMikoTimeoutException
    from netmiko.ssh_exception import AuthenticationException
    from paramiko.ssh_exception import SSHException

    username = input("Enter username:  ")
    password = getpass()
    with open('commands_file.txt') as f:
        commands_list = f.read().splitlines()
    with open('devices_list.txt') as f:
        devices_list = f.read().splitlines()
    for devices in devices_list:
        print("Connecting to device:  " + devices)
        host_name_of_device = devices
        ios_device = {
            'device_type' : 'cisco_ios' ,
            'host' : host_name_of_device ,
            'username' : username ,
            'password' : password ,
        }
        try:
            net_connect = ConnectHandler(**ios_device)
        except (AuthenticationException):
            print("Authetication failure: " + host_name_of_device)
            continue
        except (NetMikoTimeoutException):
            print("Time out from device: " + host_name_of_device)
            continue
        except (EOFError):
            print("End of File reached: " + host_name_of_device)
            continue
        except (SSHException):
            print("Not able to SSH: Try with Telnet:  " + host_name_of_device)
            continue
        except Exception as unknown_error:
            print("other: " + unknown_error)
            continue
        output = net_connect.send_config_set(commands_list)
        print(output)   
4

1 回答 1

1

netmiko 可以自动检测设备的类型。您应该在运行命令之前使用它。

from netmiko.ssh_autodetect import SSHDetect
...

    for devices in devices_list:
        print("Connecting to device:  " + devices)
        host_name_of_device = devices
        remote_device = {
            'device_type' : 'autodetect' , # Autodetect device type
            'host' : host_name_of_device ,
            'username' : username ,
            'password' : password ,
        }
        guesser = SSHDetect(**remote_device)
        best_match = guesser.autodetect()
        if best_match != 'cisco_ios':
            print("Device {} is of type {}. Ignoring "
                  "device".format(host_name_of_device, best_match))
            continue
        # Device type is cisco_ios
        remote_device['device_type'] = best_match # Detected device type
        try:
            net_connect = ConnectHandler(**remote_device)

于 2020-06-16T14:01:00.583 回答