Python中netmiko的异常处理(错误的IP地址)

huangapple go评论135阅读模式
英文:

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.)
我正在尝试为我正在制作的程序添加一个异常,以使用Python和Netmiko库登录到Cisco交换机并清除端口安全。我想提示用户输入IP地址,因此我想能够告诉他们IP地址是无效的(用户不熟悉登录到Cisco交换机并使用命令。)

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).
我看到了两个异常,并尝试为两者创建一个异常规则,也尝试了一个规则。以下是在交换机的IP无效(不存在)时出现的异常。

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 exception 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.
我想用我们的消息处理异常,这样当我部署时,它将在while循环中显示异常消息,然后再次提示输入IP。

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.
到目前为止,似乎什么都不起作用。我只是继续得到上面显示的输出。

英文:

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.

答案1

得分: 0

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)

英文:
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

huangapple
  • 本文由 发表于 2023年4月7日 04:57:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定