1

我正在尝试改进 netmiko 脚本的异常处理,该脚本成功地在文本文件中列出的 Cisco 设备上运行命令,并将连接超时的列表保存到 .txt 文件中。当我手动 SSH 到 Switch-A 时,我收到“连接关闭”错误。手动尝试切换 B 会导致连接被拒绝错误。

以下是尝试连接到 Switch-A 时的错误消息:

Connecting to device" Switch-A

Exception: Error reading SSH protocol banner

Traceback (most recent call last):

File "C:\CorpApps\Python36\lib\site-packages\paramiko-2.4.2-py3.6.egg\paramiko\transport.py", line 2138, in _check_banner

buf = self.packetizer.readline(timeout)

File "C:\CorpApps\Python36\lib\site-packages\paramiko-2.4.2-py3.6.egg\paramiko\packet.py", line 367, in readline

buf += self._read_timeout(timeout)

File "C:\CorpApps\Python36\lib\site-packages\paramiko-2.4.2-py3.6.egg\paramiko\packet.py", line 563, in _read_timeout

raise EOFError()

EOFError

SWITCH-B 的错误信息

During handling of the above exception, another exception occurred:



Traceback (most recent call last):

File "Use me #2.py", line 39, in <module>

net_connect = ConnectHandler(**ios_device)

File "C:\CorpApps\Python36\lib\site-packages\netmiko-2.3.3-py3.6.egg\netmiko\ssh_dispatcher.py", line 228, in ConnectHandler

File "C:\CorpApps\Python36\lib\site-packages\netmiko-2.3.3-py3.6.egg\netmiko\base_connection.py", line 312, in __init__

File "C:\CorpApps\Python36\lib\site-packages\netmiko-2.3.3-py3.6.egg\netmiko\base_connection.py", line 858, in establish_connection

KeyboardInterrupt



During handling of the above exception, another exception occurred:



Traceback (most recent call last):

File "Use me #2.py", line 50, in <module>

except (SSHException):

TypeError: catching classes that do not inherit from BaseException is not allowed
from netmiko import ConnectHandler
from netmiko.ssh_exception import  NetMikoTimeoutException
from paramiko.ssh_exception import SSHException 
from netmiko.ssh_exception import  AuthenticationException
from getpass import getpass
from pprint import pprint

with open('commandsv2.txt') as f:
    commands_list = f.read().splitlines()

with open('routersv3.txt') as f:
    router_list = f.read().splitlines()

username=input('Enter your username:')
password=getpass()
print (password)


for routers in router_list:
    print ('Connecting to device" ' + routers)
    ip_address_of_device = routers
    ios_device = {
    'device_type': 'cisco_ios',
    'ip': ip_address_of_device,
    'username': username,
    'password': password
    }
    
    Timeouts=open("Connection time outs.txt", "a")
    Authfailure=open("Auth failures.txt", "a")
    SSHException=("SSH Failure.txt", 'a')
    EOFError=("EOFerrors.txt",'a')
    UnknownError=("UnknownError.txt",'a')
    
    try:
        net_connect = ConnectHandler(**ios_device)  
        output=net_connect.send_config_set(commands_list)
        print(output)
    except (AuthenticationException):
        print ('Authentication Failure: ' + ip_address_of_device)
        Authfailure.write('\n' + ip_address_of_device)
        continue 
    except (NetMikoTimeoutException):
        print ('\n' + 'Timeout to device: ' + ip_address_of_device)
        Timeouts.write('\n' + ip_address_of_device)
        continue
    except (SSHException):
        print ('SSH might not be enabled: ' + ip_address_of_device)
        SSHException.write('\n' + ip_address_of_device)
        continue 
    except (EOFError):
        print ('\n' + 'End of attempting device: '  ip_address_of_device)
        EOFError.write('\n' + ip_address_of_device)
        continue
    except unknown_error:
        print ('Some other error: ' + str(unknown_error))
        continue
4

1 回答 1

0

这可能是一个迟到的答案,但我认为这很有帮助。

您将无法猜测 Netmiko 的所有异常。因此,如果您想知道异常,请尝试以下操作:

except Exception as err:
    exception_type = type(err).__name__
    print(exception_type)

您可能会得到ConnectionRefusedError,TimeoutError等。一旦您知道异常类型,请使用它而不是更通用的Exception.

例子

try:
    # Some stuff
except ConnectionRefusedError as err:
    print(f"Connection Refused: {err}")
except TimeoutError as err:
    print(f"Connection Refused: {err}")
except Exception as err:
    print(f"Oops! {err}")
于 2021-04-23T22:39:14.860 回答