'Improving exception handling of Netmiko script to SSH into Cicso devices

I'm trying to improve the exception handling of a netmiko script that successfully runs commands on Cisco devices listed in a text file and saves a list of the ones that expecience a connection timeout to a .txt file. When I SSH into Switch-A manually, I get the "connection closed" error. A manual attempt to Switch- B results in the connection refused error.

Below is the error messag when trying to connect to 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

The error message for 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


Solution 1:[1]

This might be a late answer, but I think it's helpful.

You won't be able to guess all exceptions from Netmiko. So If you want to know the exception try this out:

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

You may get ConnectionRefusedError, TimeoutError, etc. Once you know the exception type, use it instead of the more generic Exception.

Example

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}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1