In modern network operations, reactive monitoring is no longer sufficient. To predict failures before they impact users, IT teams must move from simple threshold alerting to baseline correlation. This involves comparing current Simple Network Management Protocol (SNMP) Object Identifiers (OIDs) against historical performance data to identify anomalies. By automating this process with Python, you can generate comprehensive device health reports that highlight subtle degradations in CPU utilization, memory leaks, or interface errors.
This guide provides a practical approach to building such a script using the pysnmp library in a safe, isolated lab environment. We will cover prerequisites, code implementation, workflow automation, and verification steps suitable for both students learning network automation and engineers deploying production solutions.
Prerequisites and Environment Setup
Before writing the logic, you must establish a secure test environment. Do not attempt to scan live production networks without explicit authorization; unauthorized scanning violates security policies and laws like the CFAA in the United States.
Required Tools:
* Python 3.8 or higher: Ensure your system has Python installed.
* pysnmp: The standard library for SNMP access in Python. Install it via pip:
bash
pip install pysnmp[base]
* SNMP Community String: A read-only community string (e.g., public) configured on your target device.
* Target Device: A router or switch running SNMPv2c or SNMPv3 with accessible MIBs.
Safety Note: Always run these scripts in a virtual environment (venv) to avoid conflicts with system packages. Assume all network devices in this example are within a controlled lab VLAN.
Architecting the Baseline Correlation Logic
The core challenge of device health reporting is defining “normal.” A static threshold (e.g., CPU > 80%) causes false positives during normal traffic spikes. Instead, we calculate a rolling average or baseline from historical data stored in a local database or CSV file.
The script architecture consists of three phases:
1. Data Retrieval: Fetching current OID values using SNMPv2Community.
2. Baseline Comparison: Loading historical baselines and calculating the deviation (delta).
3. Report Generation: Formatting the output into a readable PDF or HTML report if significant deviations are found.
Implementing the Python Script
Below is a concrete example of how to structure this automation. This script connects to a device, retrieves CPU and Memory OIDs, compares them against stored baselines, and logs anomalies.
from pysnmp.hlapi import *
import csv
import datetime
import os
# Configuration Variables
TARGET_IP = "192.168.10.5"
COMMUNITY_STRING = "public"
SNMP_VERSION = 2c
BASELINE_FILE = "device_baselines.csv"
REPORT_OUTPUT = "health_report.txt"
def fetch_oid_value(ip, community, oid):
"""Fetches a specific OID value from the target device."""
errorIndicators, errorStatus, errorIndex, varBinds = next(
snmpGetCmd(UdpTransportTarget(ip, 161), CommunityName(community), SnmpAuthV2c(context=0)),
None
)
if errorStatus == errorInNoNames:
return None
for varBind in varBinds:
return int(varBind[0].value)
return None
def load_baselines(file_path):
"""Loads historical baseline data from a CSV file."""
baselines = {}
if os.path.exists(file_path):
with open(file_path, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
baselines[row['device_ip']] = {
'cpu_baseline': float(row['cpu']),
'mem_baseline': float(row['memory'])
}
return baselines
def calculate_deviation(current_value, baseline):
"""Calculates the percentage deviation from baseline."""
if baseline == 0:
return 100.0 if current_value > 0 else 0.0
return ((current_value - baseline) / baseline) * 100
def generate_report():
# Define OIDs (Example: Cisco-like structure)
# 1.3.6.1.2.1.25.1.1.1 is ifInOctets (interface traffic)
# For CPU/Memory, we often use sysUpTime or specific vendor MIBs.
# Here we assume generic usage metrics for the example logic.
oids_to_monitor = {
'cpu_util': 130, # Hypothetical OID index for CPU in a custom MIB
'mem_util': 131 # Hypothetical OID index for Memory
}
baselines = load_baselines(BASELINE_FILE)
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report_lines = [f"=== Device Health Report ({current_time}) ===", ""]
device_data = baselines.get(TARGET_IP)
if not device_data:
report_lines.append(f"[WARNING] No baseline found for {TARGET_IP}. Skipping correlation.")
return "\n".join(report_lines)
# Simulated current values (In real code, call fetch_oid_value here)
# For this demonstration, we simulate a reading to show logic flow.
# In production, uncomment the fetch_oid_value calls below:
# cpu_current = fetch_oid_value(TARGET_IP, COMMUNITY_STRING, 130)
# mem_current = fetch_oid_value(TARGET_IP, COMMUNITY_STRING, 131)
# Using simulated values for demonstration purposes:
cpu_current = 45.0
mem_current = 62.0
anomalies = []
# Logic to compare current state vs baseline
cpu_deviation = calculate_deviation(cpu_current, device_data['cpu_baseline'])
mem_deviation = calculate_deviation(mem_current, device_data['mem_baseline'])
report_lines.append(f"Device: {TARGET_IP}")
report_lines.append(f"Baseline CPU: {device_data['cpu_baseline']}% | Current: {cpu_current}% (Deviation: {cpu_deviation:.2f}%)")
report_lines.append(f"Baseline Mem: {device_data['mem_baseline']}% | Current: {mem_current}% (Deviation: {mem_deviation:.2f}%)")
if abs(cpu_deviation) > 20 or abs(mem_deviation) > 15: # Thresholds for anomaly detection
report_lines.append(f"[ALERT] Significant deviation detected on {TARGET_IP}.")
anomalies.append(TARGET_IP)
if not anomalies:
report_lines.append("[STATUS] All metrics within normal historical variance.")
return "\n".join(report_lines)
if __name__ == "__main__":
print(generate_report())
Expected Results and Verification Steps
When executed successfully, the script outputs a text-based summary indicating whether device health is stable or if an alert should be triggered.
Illustrative Output:
=== Device Health Report (2023-10-27 10:45:30) ===
Device: 192.168.10.5
Baseline CPU: 25.0% | Current: 45.0% (Deviation: 80.00%)
Baseline Mem: 50.0% | Current: 62.0% (Deviation: 24.00%)
[ALERT] Significant deviation detected on 192.168.10.5.
Verification Steps:
1. Check Connectivity: Ensure the script can reach the target IP on port 161 without firewall blocks.
2. Validate MIBs: Verify that the OIDs referenced actually exist on the specific device vendor (Cisco, Juniper, etc.) using an SNMP walk tool like snmpwalk.
3. Review Baselines: Inspect the CSV file to ensure historical data is populated. If the baseline file is empty, the script will skip correlation, which is a common error state to handle gracefully.
4. Error Handling: In production, wrap the SNMP calls in try-except blocks to handle timeouts or authentication failures without crashing the entire automation job.
Automating Scheduled Jobs and Workflow Integration
A one-time script is useful for testing, but true value comes from automation. You can integrate this Python logic into a scheduled workflow using cron (Linux/macOS) or Task Scheduler (Windows).
Cron Example:
To run the health check every hour at the top of the hour:
0 * * * * /usr/bin/python3 /path/to/health_check_script.py >> /var/log/device_health.log 2>&1
Integration with Ansible:
For enterprise environments, embed this logic into an Ansible playbook. Use the community_lookup module or a custom Python script within a task to gather metrics across multiple devices in parallel, aggregating results into a single dashboard-ready JSON file. This approach scales from a single lab router to hundreds of branch office switches.
Common Mistakes and Fixes
- Mismatched Timezones: If baselines are stored with UTC timestamps but the current reading is local time, comparisons will fail. Always normalize timestamps to UTC before processing.
- Hardcoded OIDs: Network devices often use vendor-specific MIBs. Hardcoding OIDs like
1.3.6.1.4.1.9.9.109.1.1(Cisco CPU) may not work on non-Cisco hardware. Use generic OIDs where possible or implement a dynamic OID lookup table. - Ignoring SNMP Version: Older devices may only support SNMPv2c, while newer ones prefer SNMPv3. Ensure your script authenticates correctly for the specific version configured on the device.
Student Practice Task and Industry Application
Student Practice:
Set up a virtual machine running Linux with two other VMs acting as network switches. Configure one switch to return high CPU values periodically using a small background process. Write a Python script that queries both switches every 5 minutes, stores results in a CSV file, and sends an email notification only when the deviation exceeds a set limit.
Industry Application:
In a Service Provider environment, this automation feeds into a Network Operations Center (NOC) dashboard. By correlating SNMP data with historical baselines, engineers can distinguish between routine maintenance traffic spikes and genuine hardware failures requiring RMA (Return Merchandise Authorization). This proactive approach reduces Mean Time to Repair (MTTR) significantly.
Conclusion
Automating device health reporting by correlating SNMP OIDs with historical baselines transforms network monitoring from a passive logging exercise into an active diagnostic tool. By following the steps outlined above—setting up a secure lab, implementing the Python logic, and integrating scheduled jobs—engineers can build robust systems that alert on anomalies before they become outages. Remember to always verify policy terms regarding data retention and privacy when handling network telemetry in production environments.
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.

