我正在尝试改进 netmiko 脚本的异常处理,该脚本在文本文件中列出的 Cisco 设备上成功运行命令,并将遇到连接超时的设备列表保存到 .txt 文件。当我手动通过 SSH 连接到交换机 A 时,出现“连接已关闭”错误。手动尝试 Switch-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
这可能是一个迟到的答案,但我认为它很有帮助。
您无法猜出 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}")