In high-availability network environments, scheduled maintenance windows are critical opportunities for upgrades and troubleshooting. However, the greatest risk lies not in the work itself, but in proceeding without confirming that the current state is stable. A router with a flapping neighbor or an undetected adjacency failure can cause cascading outages if maintenance tools inadvertently clear routing tables or restart control planes. For IT students and junior engineers, mastering the automation of these checks using Python provides a significant career advantage over manual CLI inspection. This guide demonstrates how to build a robust Python script that verifies Open Shortest Path First (OSPF) neighbor states across multi-vendor routers before a maintenance event begins.
Understanding the Risks of Manual Verification
Before writing code, it is essential to understand why automation is necessary in this context. Network administrators often rely on command-line interfaces (CLI) such as show ip ospf neighbor on Cisco devices or display ospf peer on Huawei/H3C equipment. While effective for single devices, this approach fails at scale. Human error occurs when skipping a device, misreading the “Full” state in a dense output, or forgetting to check non-Cisco vendors like Juniper or Nokia (formerly Alcatel-Lucent).
Furthermore, manual checks are static snapshots. By the time an administrator finishes checking Router B, Router A might have already dropped a neighbor relationship due to a timer expiration. Automation ensures that every device in the scope is checked consistently, with timestamps recorded for audit trails. This script focuses on detecting the “Full” state, which indicates a fully established adjacency where LSAs (Link State Advertisements) are synchronized.
Prerequisites and Environment Setup
To run this script effectively, you need a Python environment installed on your workstation or server. We will assume Python 3.8 or higher. The primary library required is netmiko, which abstracts the complexities of different vendor CLIs into a unified interface.
First, install the necessary dependencies:
pip install netmiko jinja2 paramiko
Network Prerequisites:
1. SSH Access: You must have SSH credentials (username/password or SSH keys) for every router in your inventory.
2. Inventory File: A text file (e.g., inventory.txt) containing one device per line with the hostname, platform type, and connection parameters.
3. Safe Lab Environment: Do not run this against production networks without strict approval. This script is designed for lab practice or pre-approved maintenance windows.
The Python Script Logic
The script uses a dictionary to map device hostnames to their specific connection details. It then iterates through this list, establishes an SSH session, executes the vendor-specific command to check OSPF neighbors, and parses the output to look for the string “Full”.
from netmiko import ConnectHandler
import json
import sys
# Define your inventory of routers
# Note: Replace with actual hostnames and credentials for your lab
inventory = {
'core-router-01': {
'device_type': 'cisco_ios',
'host': '192.168.10.1',
'username': 'admin',
'password': 'cisco123',
'port': 22,
'platform': 'cisco_ios'
},
'core-router-02': {
'device_type': 'juniper_junos',
'host': '192.168.10.2',
'username': 'admin',
'password': 'junos123',
'port': 22,
# Juniper uses a different command structure
},
'edge-router-01': {
'device_type': 'cisco_ios',
'host': '192.168.20.1',
'username': 'admin',
'password': 'cisco123',
'port': 22,
}
}
def check_ospf_neighbors(device_info):
try:
print(f"Connecting to {device_info['host']}...")
connection = ConnectHandler(**device_info)
# Vendor-specific commands to show OSPF neighbors
if device_info['device_type'] == 'cisco_ios':
command = "show ip ospf neighbor"
elif device_type == 'juniper_junos':
command = "show route protocol ospf" # Juniper often shows adjacency via routes or specific peer commands
output = connection.send_command(command)
# Parse the output to find "Full" state (Cisco) or equivalent for others
# This is a simplified regex approach; production scripts might use more robust parsing
if 'FULL' in output:
print(f"[OK] {device_info['host']}: OSPF neighbors are fully established.")
return True
else:
print(f"[WARN] {device_info['host']}: No 'Full' state detected in neighbor list. Check adjacency.")
return False
except Exception as e:
print(f"[ERROR] Failed to connect to or query {device_info['host']}: {str(e)}")
return False
# Execute the check for all devices
results = []
for hostname, info in inventory.items():
# Special handling for Juniper example logic above would go here
# For this demonstration, we assume a generic 'FULL' string search for Cisco
result = check_ospf_neighbors(info)
results.append({hostname: result})
print("\n--- Maintenance Readiness Report ---")
for item in results:
print(item)
Interpreting Results and Expected Output
When the script runs successfully, it outputs a clear status for each device. In a healthy environment, you will see messages indicating [OK] alongside the hostname. The illustrative output confirms that the adjacency state is “Full” on all specified routers.
However, if the script returns [WARN], it indicates that the OSPF neighbor list either does not contain a “Full” entry or the parser failed to detect it. This could mean:
1. The neighbor relationship is in DOWN or INIT state.
2. There is an authentication mismatch.
3. A network layer issue (Layer 1/2) is preventing Hello packet reception.
Illustrative Output:
[OK] 192.168.10.1: OSPF neighbors are fully established.
[WARN] 192.168.10.2: No 'Full' state detected in neighbor list. Check adjacency.
--- Maintenance Readiness Report ---
{'core-router-01': True, 'core-router-02': False}
Common Errors and Troubleshooting Fixes
When deploying this automation, you will encounter specific errors that require immediate attention:
- Authentication Failure: The most common error is
Authentication timeoutorSSH connection closed. This usually means the username/password in your inventory file does not match the device configuration. Ensure you are using enable mode credentials for Cisco devices if the command requires elevated privileges, thoughshow ip ospf neighbortypically runs in user exec mode. - Platform Mismatch: If you use
netmiko, ensure thedevice_typematches the actual OS (e.g.,cisco_ios_xevscisco_ios). Using the wrong type causes parsing errors where the command output is not recognized. - Parsing Logic Gaps: The script above uses a simple string search for “FULL”. On some vendors, the output might display “Full” in lowercase or use different formatting. Always inspect the raw output (
outputvariable) during development to refine your parsing logic.
Student Practice Task and Industry Application
For students and junior engineers, the next step is to modify this script to generate a JSON report saved to a file. This simulates a real-world DevOps workflow where logs are collected for later analysis.
Student Challenge:
Modify the script to:
1. Accept a command-line argument for the inventory file path.
2. Append a timestamp to every log entry.
3. Save the final report as ospf_maintenance_report.json.
Industry Application:
In a professional setting, this script is integrated into a CI/CD pipeline or scheduled via cron jobs (Linux) or Task Scheduler (Windows). A typical workflow might look like this:
1. 08:00: Script runs automatically to verify network stability.
2. 09:00: If all checks pass, the system automatically approves a ticket for planned maintenance.
3. Failure Handling: If a check fails, the script can be configured to send an alert to Slack or email, preventing the maintenance window from starting until the issue is resolved.
Final Checklist for Maintenance Windows
Before executing any maintenance task involving OSPF routers, run this mental and automated checklist:
* [ ] Are all OSPF neighbors in the “Full” state?
* [ ] Have you verified that no interfaces are flapping (oscillating up/down)?
* [ ] Is the script running against a non-production copy of your inventory?
* [ ] Do you have a rollback plan if the automation script itself fails during maintenance?
By automating these checks, you eliminate human error and ensure that your network infrastructure is in a known-good state before any changes are deployed.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

