改进Netmiko脚本的异常处理以通过SSH进入Cicso设备

时间:2019-04-29 18:31:49

标签: python-3.x networking network-programming cisco

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

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

连接到设备“ Switch-A

异常:读取SSH协议标语时出错

回溯(最近通话最近一次):

_check_banner中的第2138行,文件“ C:\ CorpApps \ Python36 \ lib \ site-packages \ paramiko-2.4.2-py3.6.egg \ paramiko \ transport.py”

buf = self.packetizer.readline(timeout)

readline中的第367行“文件C:\ CorpApps \ Python36 \ lib \ site-packages \ paramiko-2.4.2-py3.6.egg \ paramiko \ packet.py”

buf + = self._read_timeout(timeout)

文件“ C:\ CorpApps \ Python36 \ lib \ site-packages \ paramiko-2.4.2-py3.6.egg \ paramiko \ packet.py”,第563行,在_read_timeout中

提高EOFError()

EOFError


SWITCH-B的错误消息

在处理上述异常期间,发生了另一个异常:

回溯(最近通话最近一次):

中的文件“ Use me#2.py”,第39行

net_connect = ConnectHandler(** ios_device)

ConnectHandler中的文件“ C:\ CorpApps \ Python36 \ lib \ site-packages \ netmiko-2.3.3-py3.6.egg \ netmiko \ ssh_dispatcher.py”,第228行

文件“ C:\ CorpApps \ Python36 \ lib \ site-packages \ netmiko-2.3.3-py3.6.egg \ netmiko \ base_connection.py”,第312行,位于 init < / p>

在build_connection中的文件“ C:\ CorpApps \ Python36 \ lib \ site-packages \ netmiko-2.3.3-py3.6.egg \ netmiko \ base_connection.py”,第858行

KeyboardInterrupt

在处理上述异常期间,发生了另一个异常:

回溯(最近通话最近一次):

中的文件“ Use me#2.py”,第50行

除了(SSHException):

TypeError:不允许捕获不继承自BaseException的类

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

1 个答案:

答案 0 :(得分:0)

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

您将无法猜测 Netmiko 的所有例外情况。所以如果你想知道异常,试试这个:

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

您可能会得到 ConnectionRefusedErrorTimeoutError 等。一旦您知道异常类型,请使用它而不是更通用的 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}")