Search code examples
python-3.xrouterparamikocisconetmiko

Exception handling for netmiko in Python(bad ip address)


I am trying to give an exception for a program I am making to log into a Cisco switch and clear Port sec using Python and the Netmiko library. I would like to prompt the user for the IP address, so I would like to be able to let them know the IP address is bad(the user is not familiar with logging into cisco switches and using commands.) I see two exceptions and have tried to create one exception rule for both, and also tried one for each. Here is the exception that comes when the IP of a switch is bad(does not exist). *> Traceback (most recent call last):

Output

File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\netmiko\base_connection.py", line 1046, in establish_connection self.remote_conn_pre.connect(**ssh_connect_params) File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\paramiko\client.py", line 340, in connect to_try = list(self._families_and_addresses(hostname, port)) File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\paramiko\client.py", line 203, in _families_and_addresses addrinfos = socket.getaddrinfo( File "C:\Users\jesse.garcia\Anaconda3\lib\socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\jesse.garcia\Documents\GitHub\python\Practice OOP\practicce.py", line 18, in <module> net_connect = ConnectHandler(**cisco_881) File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\netmiko\ssh_dispatcher.py", line 365, in ConnectHandler return ConnectionClass(*args, **kwargs) File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\netmiko\base_connection.py", line 439, in init self._open() File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\netmiko\base_connection.py", line 444, in _open self.establish_connection() File "C:\Users\jesse.garcia\Anaconda3\lib\site-packages\netmiko\base_connection.py", line 1068, in establish_connection raise NetmikoTimeoutException(msg) netmiko.exceptions.NetmikoTimeoutException: TCP connection to device failed.

Common causes of this problem are: Incorrect hostname or IP address. Wrong TCP port. Intermediate firewall blocking access.

Device settings: cisco_ios +95:22*

Here is what I have for code:

from netmiko import ConnectHandler
import netmiko
import paramiko
import socket

ipadd = input("Please enter the IP address of the switch ")
port = input("Please enter the port ")
cisco_881 = {
    'device_type': 'cisco_ios',
    'host':   ipadd,
    'username': '',
    'password': '',
    'port' : 22,          # optional, defaults to 22
    'secret': '',     # optional, defaults to ''
}

if __name__ == "__main__":
    net_connect = ConnectHandler(**cisco_881)
    

    try:
        net_connect.send_command(f'clear port-security sticky int g1/0/{port}')
    except (socket.gaierror, netmiko.exceptions.NetmikoTimeoutException):
        print("Ip address is bad. ")



I would like to handle the excetion with a message of ours so that when I deploy, it will be in a while loop and show the exception message, then prompt for the IP again.

I have also tried to use this piece of code to see what exactly the interpreter is seeing.

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

as well as:

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

So far nothing seems to work. I just keep getting the output shown above.


Solution

  • from pprint import pprint
    from netmiko import ConnectHandler
    
    
    if __name__ == "__main__":
        ip_add = input("Please enter the IP address of the switch:-")
        port = input("Please enter the port:-")
        cisco_881 = {
        'device_type': 'cisco_ios',
        'host':   ip_add,
        'username': '',
        'password': '',
        'port' : 22,          # optional, defaults to 22
        'secret': '',     # optional, defaults to ''
        }
        result = {}
        command = f'clear port-security sticky int g1/0/{port}'
        try:
            with ConnectHandler(**cisco_881) as ssh:
                print('enabling wait...')
                ssh.enable()
                output = ssh.send_command(command)
                result[command] = output
        except Exception:
            print("Ip address is bad.")
        pprint(result, width=120)
    

    For more info refer to documentation:- https://pyneng.readthedocs.io/en/latest/book/18_ssh_telnet/netmiko.html