Applying an exception when rolling a Python script on Huawei

We usually encounter three problems when trying to run a Python script on a Huawei network (or any other network): L3 connectivity to the device is missing, the username or password is incorrect, and SSH is a problem. It can be seen that any of these problems will stop the script from rolling forward and generate the same log, most of which is difficult to understand. In this article, I tried to talk about a small improvement to the previous code, which will report a specific error on the device, and continue to roll the script further.

Running the code can be seen at demo video.

Outputting the error log without using the try - except - continue construct
Outputting the error log without using the try – except – continue construct

I will use Python construct try – except – continue. try allows you to test a block of code for errors. except (exception or exceptions) is a Python data type that allows you to report an error. Most exceptions are already defined and built into Python, you just need to find the right one.

I will also use the operator continueso that the script will continue to roll forward despite an error. A function print() prints the given message if an exception is thrown. In other words, if it fails to connect to a device from the list of devices, the script will display a short message why it failed to connect, and will try to connect to the next device, and so on. If no error occurs, then the except code is skipped. I emphasize once again that the occurrence of an error without the try – except – continue construct, firstly, immediately stops the script from running, that is, there is no attempt to connect to other devices from the list, and secondly, the generated message log is long and empty.

So, Python has built-in exceptions that describe specific errors. For example:

Authentication Error – AuthenticationException

Unreachable error – NetMikoTimeoutException

SSH Error – SSHException

code block except fires only if an error occurs. This block contains the print() function and the continue statement. For example, if you enter an incorrect password, the message “Invalid authentication data: device ip address” will be displayed on the screen. If none of the errors occur, then all three except code blocks will be skipped, and only the main task of the script will work – send_config_set (the last line of code in the example above).

All specified exceptions must be imported through the appropriate modules:

from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException

I will give the entire code at the end of the article.

Now test in eNSP. There are eight CloudEngine Huawei switches in the topology. Of these, I will enable only three, the remaining five will remain inaccessible (when trying to connect to them, the script should display the message “No response from device: ip-address”). I will leave the first switch without errors, that is, the automation task (configuration rollover) should work on it, on the second I will change the password, and on the third I will disable SSH.

eNSP topology for error handling testing
eNSP topology for error handling testing

Change password to CE2:

sys

Enter system view, return user view with return command.

[~CE_2]aaa

[~CE_2-aaa]local-user vasyo1 password irreversible-cipher @ghjcnjnF3589866

[*CE_2-aaa]commit

Disable SSH on VTY lines on CE_3:

sys

Enter system view, return user view with return command.

[~CE_3]user-interface vty 0 4

[~CE_3-ui-vty0-4]protocol inbound telnet

[*CE_3-ui-vty0-4]commit

Now I will run the script:

Applying an exception when rolling a Python script on Huawei
Applying an exception when rolling a Python script on Huawei

The first lines after Password are the contents of the JSON files, namely the file containing the configuration commands and the file containing the list of device IP addresses. Further, in the first red rectangle, a successful configuration rollover, in the second red rectangle, a message about incorrectly entered authentication data (where I changed the password), and the third rectangle reports that SSH is unavailable (where I allowed only telnet). The remaining five switches: no response from the device and their IP addresses (which I did not include).

We can talk about the successful application of the design try – except – continue.

Can watch the video demo, source code and its description in the article: My friend Netmiko. Part 2: Three improvements to the Python script.

Full code:

from getpass import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException

username = input('Введите имя пользователя SSH: ')
password = getpass()

with open('switch_file_config') as f:
    config_lines = f.read().splitlines()
print (config_lines)

with open('myswitches') as f:
    ip_lines = f.read().splitlines()
print (ip_lines)

for device in ip_lines:
    ip_address_of_device = device
    CE = {
        'device_type': 'huawei',
        'ip':   ip_address_of_device,
        'username': username,
        'password': password
    }

    try:
        ssh_connect = ConnectHandler(**CE)
    except (AuthenticationException):
        print ('Неверные данные аутентификации: ' + ip_address_of_device)
        continue
    except (NetMikoTimeoutException):
        print ('Нет ответа от устройства: ' + ip_address_of_device)
        continue
    except (SSHException):
        print ('SSH недоступен. Проверьте включен ли SSH? ' + ip_address_of_device)
        continue

    output = ssh_connect.send_config_set(config_lines)
    print(f"\n\n-------------- CE_{CE['ip']} --------------")
    print(output)
    print("-------------------- End -------------------")

Literature:

https://stackoverflow.com/questions/5563089/raw-input-function-in-python

https://pynet.twb-tech.com/blog/automation/netmiko.html

https://pyneng.readthedocs.io/en/latest/book/18_ssh_telnet/netmiko.html

https://github.com/ktbyers/netmiko

https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py

Udemy.com – Python Network Programming for Network Engineers (Python 3) (David Bombal)

https://www.pythoncentral.io/pythons-range-function-explained

Similar Posts

Leave a Reply