In modern network operations centers, legacy multi-vendor environments often persist alongside newer infrastructure. These older devices may lack support for modern telemetry protocols like gNMI or Telemetry streams, relying instead on Simple Network Management Protocol (SNMP). A common pain point is the accumulation of interface errors—collisions, CRCs, and input drops—that are not immediately visible in standard monitoring dashboards without active polling. This guide walks you through building a custom Python-based SNMP poller using pysnmp to batch-collect these metrics from heterogeneous switch fleets.
Prerequisites and Environment Setup
Before writing code, ensure your environment meets the following requirements. This project assumes a Linux or macOS environment, though Windows with WSL2 is also viable for development.
- Python Version: Install Python 3.8 or higher.
- SNMP Libraries: The
pysnmplibrary provides robust SNMPv1/v2c/v3 support. You will also needjinja2for templating andschedulefor cron-like functionality within Python.
bash
pip install pysnmp jinja2 schedule python-dotenv - SNMP Configuration on Devices: Ensure every target switch has a valid SNMP community string configured (e.g.,
public) or an SNMPv3 user with appropriate read-view permissions. Note that for security, SNMPv3 is preferred in production, but this example focuses on the mechanics of polling using v2c for legacy compatibility. - Network Connectivity: Confirm you can reach the management IP addresses of the switches from your server and that UDP port 161 is open (firewall rules permitting).
Designing the Poller Architecture
The architecture consists of three logical layers: a configuration loader, the polling engine, and an alert/report generator.
Configuration Management
Hardcoding IPs in scripts is error-prone. Instead, store device details in a YAML or JSON file. This allows Ansible or other orchestration tools to manage the inventory dynamically. Create a file named inventory.yaml:
devices:
- hostname: "legacy-cisco-01"
ip: "192.168.10.5"
community: "public"
version: 2c
max_retries: 3
- hostname: "legacy-juniper-01"
ip: "192.168.10.20"
community: "private"
version: 2c
max_retries: 3
The Polling Engine Logic
The core logic involves iterating through the inventory, constructing SNMP trees (OIDs), and parsing responses. The primary OID for interface errors varies by vendor but generally falls under ifXTable or specific vendor extensions. For Cisco, common error counters include ifInErrors and ifOutErrors.
Here is a robust polling function using pysnmp:
from pysnmp.carro import context, mib, asn1, comp
from pysnmp.smi import builder, entity
from pysnmp.proto import rfc1902
from pysnmp.hlapi import *
def poll_interface_errors(device_config):
ip_address = device_config['ip']
community = device_config['community']
version = device_config['version']
# Initialize SNMP context
errorIndications = []
def handle_error(status, varBindTable):
if status:
errorIndications.append(f"Error on {device_config['hostname']}: {status}")
else:
print(f"Successfully polled {device_config['hostname']}")
# Walk the ifXTable (generic interface table)
# Note: OIDs may need adjustment based on specific MIBs installed on legacy devices
error_counter_oid = Integer32(1, 6, 3, 1, 2, 1, 2, 1, 1, 1)
walk_result = (
snmpWalk(context=DefaultUdpTransportTarget(ip_address, 161, community),
version=snmpVersionSnmpv2c,
securityName='',
secModel=secModelNoAuthNoPriv,
authProtocol=authProtocolNone,
privProtocol=privProtocolNone)
.nextTo(oid=error_counter_oid)
.addHandler(handle_error)
)
return walk_result
# Usage example
device_list = load_inventory() # Function to parse YAML
for device in device_list:
poll_interface_errors(device)
Handling Multi-Vendor Heterogeneity
One of the greatest challenges in legacy environments is that OIDs are not always consistent. While ifXTable is standard, some older switches use proprietary extensions or require specific MIB files to be loaded locally before polling can succeed.
Vendor-Specific Considerations
- Cisco: Generally adheres strictly to RFC 1213 and SMIv2 standards for interface tables.
- Juniper: Often uses the same standard OIDs but may have different community string naming conventions or require SNMPv3 authentication even if v2c is technically supported.
- Legacy HP/Comware: May require loading a specific MIB file (e.g.,
CISCO-CAM-MIBor vendor-specific archives) before the OID resolves correctly in the client library.
In your Python script, include a mechanism to handle “No Such Name” errors gracefully. If an OID fails, log the attempt and move to the next device rather than crashing the entire batch job. This ensures partial failures do not stop data collection for healthy devices.
Expected Output and Verification
When the script runs successfully, you should see output indicating which devices were polled and any specific error messages encountered.
Successfully polled legacy-cisco-01
Error on legacy-juniper-01: Timed Out (Connection refused or firewall block)
Successfully polled legacy-hp-01
To verify the data, parse the returned varBindTable objects and convert them into a structured format like JSON or CSV for ingestion into a reporting tool.
Automating with Scheduled Jobs and Ansible
Running the script manually is insufficient for production monitoring. You must integrate this into a workflow automation pipeline.
Implementing Cron Jobs
On Linux/Unix systems, create a cron job to run your Python poller every 5 minutes:
# Edit crontab
crontab -e
# Add the following line (runs every 5 minutes)
*/5 * * * * /usr/bin/python3 /path/to/snmp_poller.py >> /var/log/snmp_poller.log 2>&1
Integrating with Ansible
For larger fleets, use Ansible to manage the execution of the poller or even push configuration updates to the switches before polling. You can write an Ansible playbook that calls your Python script as a module or executes it via shell. This ensures that if a device reboots or its community string changes, the inventory is updated centrally without touching every device individually.
Common Mistakes and Troubleshooting
When developing this poller, several pitfalls frequently arise:
- Community String Mismatch: The most common error is an “Access Denied” response. Always verify that the community string in your script matches exactly what is configured on the switch (case-sensitive).
- Timeout Issues: Legacy switches with high CPU loads may not respond to SNMP requests within the default timeout window. Increase the
timeoutandretryCountparameters in yoursnmpWalkcall. - MIB Loading Failures: If you receive “No Such Name” errors, check if the required MIB files are installed in your Python environment’s MIB directory (
/usr/share/snmp/mibs). - Firewall Blocks: Ensure UDP port 161 is open between your monitoring server and the switch management VLANs.
Student Practice Task
To solidify your understanding, try this exercise:
1. Set up two virtual machines (one as a “server,” one as a “switch”).
2. Configure SNMPv2c on the VM acting as the switch using snmpd.
3. Write a Python script that polls the interface table and outputs a JSON file containing the device name, IP, and current input error count.
4. Extend the script to handle a “timeout” scenario by logging the failure without stopping execution.
Industry Application and Security Considerations
In a real-world enterprise setting, this poller feeds into a central SIEM (Security Information and Event Management) or ticketing system like ServiceNow. When interface errors spike above a threshold (e.g., >100 per minute), the script can trigger an alert to notify network engineers.
Security Note: While this guide uses SNMPv2c for legacy compatibility, it is crucial to acknowledge that community strings are essentially plain-text passwords. In production environments where possible, migrate these devices to SNMPv3, which supports authentication and encryption. If migration is not immediately possible, restrict SNMP access via ACLs (Access Control Lists) to only allow the monitoring server’s IP address.
Always consult your organization’s security policy before deploying custom polling scripts that interact with network infrastructure. Terms, availability, eligibility, laws, and prices regarding network management tools depend on vendor licensing, local jurisdiction regulations, and specific organizational policies. Never assert live premiums or specific legal rules as current without verification from official documentation or legal counsel.
By building a custom poller, you gain visibility into the health of your entire infrastructure, bridging the gap between legacy hardware and modern observability platforms.
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.

