Click the mini-program card below to view the original post for more content
1. Background
As the number of network devices increases, the workload of manually checking configurations significantly rises, leading to potential omissions or misjudgments. To enhance the efficiency and accuracy of configuration checks, it is necessary to leverage Python to build automated checking capabilities. This article uses the example of checking for missing key configurations in Huawei network devices to illustrate how to use a Python script to batch check whether device configurations are complete.
2. Python Environment Installation
Environment Description: The operating system for the installation environment is openEuler 22.03 LTS SP3/24.03 LTS, supporting online installation via dnf and pip.
Installation Tools: You need to install the system tool dnf package manager, Python software (version 3.12.2), and network engineering software paramiko (version 3.3.4), netmiko (version 4.2.0).
Detailed Steps:
(1) System Dependency Installation: The command is dnf install -y gcc make zlib-devel libffi-devel openssl-devel wget.
(2) Python 3.12 Installation: The command is dnf install -y python3.12 python3.12-pip.
(3) Network Engineering Software Installation: The commands are pip3.12 install paramiko and pip3.12 install netmiko.
(4) Installation Verification: The command is python3.12 –version # Should output 3.12.2.
3. Python Script Description
To check for missing key configurations in Huawei network devices, the script needs to log into the devices based on a predefined list of mandatory items, read the configurations, and compare them item by item.
(1) Script Function Description
Obtain Authentication Information: The script prompts the user to input the SSH username and password at runtime, supporting only SSH login to the devices.
Read Device IPs: Automatically reads the contents of the huawei_ip.txt file in the same directory as the script, with each line representing a management IP of a device, enabling batch checks across multiple devices.
Load Mandatory Item List: Reads the mandatory configuration items from the huawei_mandatory_config.txt file in the same directory as the script, with each line representing a key configuration (e.g., ACL rules, VLAN configurations, routing entries, etc.).
SSH Login to Devices: Establishes an SSH connection to the devices using the paramiko library, and upon successful connection, prompts “Successful connect to the device [IP]”.
Read Device Configuration: Sends the display current-configuration command to obtain the current running configuration of the device, ensuring complete reading without screen truncation.
Configuration Missing Comparison: Compares the actual device configuration with the mandatory item list item by item, recording missing configuration items and the reasons for unmatched items.
Generate Check Report: After the script execution is complete, a file named “Configuration Check Report – Date.txt” is generated in the current directory, detailing the check results for each device.
(2) Script Details
#!/usr/bin/python3# Function: Batch SSH login to Huawei network devices, check for missing key configurations and generate reportsimport paramikoimport timefrom datetime import datetimeimport getpass# 1. Get SSH authentication information (hide password input)username =input("Please enter SSH username:")password = getpass.getpass("Please enter SSH password:")# Password is not echoed during input# 2. Read device IP list (huawei_ip.txt in the same directory as the script)try:withopen("huawei_ip.txt","r", encoding="utf-8")as ip_file: ip_list =[ip.strip()for ip in ip_file if ip.strip()]# Remove empty lines and spacesifnot ip_list:print("Error: No valid IP addresses found in huawei_ip.txt") exit()except FileNotFoundError:print("Error: huawei_ip.txt file not found in the same directory as the script") exit()# 3. Read mandatory configuration item list (huawei_mandatory_config.txt in the same directory as the script)try:withopen("huawei_mandatory_config.txt","r", encoding="utf-8")as cfg_file: mandatory_configs =[cfg.strip()for cfg in cfg_file if cfg.strip()]# Remove empty lines and spacesifnot mandatory_configs:print("Error: No valid mandatory configuration items found in huawei_mandatory_config.txt") exit()except FileNotFoundError:print("Error: huawei_mandatory_config.txt file not found in the same directory as the script") exit()# 4. Initialize report-related informationreport_date = datetime.now().strftime("%Y%m%d_%H%M%S")report_filename =f"Configuration Check Report-{report_date}.txt"total_devices =len(ip_list)success_devices =0failed_devices =[]# 5. Process each device in batchfor ip in ip_list: ssh_client =Nonetry:# 5.1 Establish SSH connection ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect( hostname=ip, username=username, password=password, timeout=10, allow_agent=False, look_for_keys=False)print(f"\n Successfully connected to device: {ip}") success_devices +=1# 5.2 Enter interactive shell, send command (disable screen) command = ssh_client.invoke_shell() time.sleep(1) command.send("screen-length 0 temporary\n") time.sleep(1)# 5.3 Read the current running configuration of the deviceprint(f"Getting current running configuration of {ip}...") command.send("display current-configuration\n") time.sleep(8)# Adjust wait time based on device configuration complexity device_config = command.recv(1048576).decode("utf-8", errors="ignore")# Expand receive buffer# 5.4 Compare mandatory configuration items, record missing items missing_configs =[]for cfg in mandatory_configs:if cfg notin device_config: missing_configs.append(cfg)# 5.5 Record the check result for each device in the reportwithopen(report_filename,"a", encoding="utf-8")as report_file: report_file.write(f"===== Device IP: {ip} - Check Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====\n") report_file.write(f"Total Mandatory Configuration Items: {len(mandatory_configs)}\n")if missing_configs: report_file.write(f"Number of Missing Configuration Items: {len(missing_configs)}\n") report_file.write("Missing Configuration Items:\n")for idx, missing inenumerate(missing_configs,1): report_file.write(f"{idx}. {missing}\n")else: report_file.write("Check Result: All mandatory configuration items are present, configuration is complete\n") report_file.write("="*80+"\n\n")print(f"{ip} check completed: {len(mandatory_configs)} mandatory items, {len(missing_configs)} missing")except Exception as e:print(f"\n Check failed for device {ip}: {str(e)}") failed_devices.append(f"{ip} - Failure Reason: {str(e)}")# Record failure information in the reportwithopen(report_filename,"a", encoding="utf-8")as report_file: report_file.write(f"===== Device IP: {ip} - Check Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====\n") report_file.write(f"Check Result: Connection or command execution failed, failure reason: {str(e)}\n") report_file.write("="*80+"\n\n")finally:if ssh_client: ssh_client.close()# 6. Write summary information to the reportwithopen(report_filename,"a", encoding="utf-8")as report_file: report_file.write("===== Check Summary =====\n") report_file.write(f"Total Checked Devices: {total_devices}\n") report_file.write(f"Successfully Checked Devices: {success_devices}\n") report_file.write(f"Failed Checked Devices: {len(failed_devices)}\n")if failed_devices: report_file.write("Failed Device Details:\n")for idx, failed inenumerate(failed_devices,1): report_file.write(f"{idx}. {failed}\n")print(f"\nAll device checks completed! Check report generated: {report_filename}")
4. Checking for Missing Configurations in Huawei Network Devices
1. Preparation: Copy the script to the target directory of the Euler system, naming it huawei_config_check.py; create huawei_ip.txt in that directory, filling in the management IP of the devices to be checked (one per line); create huawei_mandatory_config.txt, filling in the mandatory configuration items (one per line, such as “vlan 10”, “acl number 3000”, “ip route-static 0.0.0.0 0.0.0.0 192.168.1.1”); ensure that the device’s SSH service is enabled and the network is reachable.
2. Script Execution: Execute the command python3 huawei_config_check.py; input SSH username and password; the script automatically reads the IP list and mandatory item list, completing device login, configuration reading, and missing comparison in batch.
3. Result Viewing: After the script execution is complete, a timestamped file named “Configuration Check Report – xxx.txt” will be generated in the current directory, where you can view the matching status of mandatory items for each device, details of missing configurations, and overall check summary.
This article is published by WINDWOLF in the community, and reproduction is prohibited without the author’s permission.


