HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 14 of 20 — Python for Network Engineers
intermediate Chapter 14 of 20

SNMP Monitoring with Python — pysnmp, Polling & Trap Handling

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

SNMP Fundamentals — Versions, Community Strings & MIBs

Simple Network Management Protocol (SNMP) serves as the backbone of network monitoring, enabling administrators to manage and monitor network devices efficiently. Understanding SNMP fundamentals is essential before diving into SNMP Python monitoring using libraries like pysnmp. SNMP operates across multiple versions, each introducing enhancements in security and functionality. SNMPv1 and SNMPv2c are widely used, primarily due to their simplicity and ease of deployment, but they lack robust security features. SNMPv3, on the other hand, provides encryption, authentication, and access control, making it suitable for sensitive environments.

At its core, SNMP uses community strings—essentially passwords—that grant access to device data. Common community strings include "public" (read-only) and "private" (read-write), but these default values pose security risks and should be changed in production environments. Community strings are included in SNMP messages to authenticate requests and responses.

Managed devices maintain Management Information Bases (MIBs), which are hierarchical databases containing all accessible parameters—like interface statuses, CPU utilization, or traffic counters. MIBs define the structure of the data and its identifiers, enabling network management tools to interpret raw SNMP data correctly. When performing SNMP polling, understanding MIBs is crucial to craft accurate OID (Object Identifier) queries to retrieve specific metrics.

In practice, effective SNMP monitoring hinges on selecting the appropriate SNMP version, configuring secure community strings, and leveraging MIBs to extract meaningful insights. This foundational knowledge allows network engineers to automate device health checks, troubleshoot issues, and optimize network performance seamlessly.

pysnmp Library — Installation & Basic GET/WALK Operations

The pysnmp library is a comprehensive Python toolkit for implementing SNMP operations, making it the perfect choice for building SNMP Python monitoring scripts. Installing pysnmp is straightforward using pip:

pip install pysnmp

Once installed, you can perform basic SNMP GET and WALK operations. These are fundamental for retrieving specific OID values or exploring device MIBs to discover available data points.

Performing an SNMP GET

The GET operation retrieves the value of a specific OID from a network device. For example, to fetch the sysUpTimeInstance (OID: 1.3.6.1.2.1.1.3.0), use the following Python code:

from pysnmp.hlapi import *

iterator = getCmd(
    SnmpEngine(),
    CommunityData('public', mpModel=0),
    UdpTransportTarget(('192.168.1.1', 161)),
    ContextData(),
    ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'))
)

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    for varBind in varBinds:
        print(' = '.join([x.prettyPrint() for x in varBind]))

This script connects to a device at 192.168.1.1, fetches the system uptime, and displays it. Similarly, the SNMP WALK operation can be used to traverse entire MIB branches, which is invaluable during device discovery and troubleshooting.

Performing an SNMP WALK

def snmp_walk(target_ip, community, base_oid):
    for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(
        SnmpEngine(),
        CommunityData(community, mpModel=0),
        UdpTransportTarget((target_ip, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(base_oid)),
        lexicographicMode=True
    ):
        if errorIndication:
            print(errorIndication)
            break
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            break
        else:
            for varBind in varBinds:
                print(' = '.join([x.prettyPrint() for x in varBind]))

snmp_walk('192.168.1.1', 'public', '1.3.6.1.2.1.2')  # Interface MIBs

This function walks through interface-related MIBs, listing all interface statuses and counters, essential for comprehensive network analysis.

Mastering these basic operations with pysnmp sets the stage for advanced network monitoring automation, allowing engineers to script repetitive tasks efficiently. For a detailed pysnmp tutorial, visit the Networkers Home Blog, which offers practical insights and code snippets.

Polling Network Devices — Interface Stats, CPU & Memory

Effective SNMP Python monitoring relies on regularly polling network devices to collect vital statistics. Typical metrics include interface utilization, CPU load, and memory usage—key indicators of device health. Automating this process reduces manual effort and enhances real-time visibility into network performance.

Polling is implemented by executing SNMP GET or GETNEXT requests at scheduled intervals. For example, to monitor interface bandwidth utilization, you might poll the ifInOctets (OID: 1.3.6.1.2.1.2.2.1.10) and ifOutOctets (OID: 1.3.6.1.2.1.2.2.1.16) for each interface.

Polling Interface Statistics

Using pysnmp, a script can query multiple interface counters and compute utilization percentages over time. Here’s an example snippet for polling interface input octets:

import time

def poll_interface_stats(target_ip, community, interface_oid_base):
    in_octets_oid = interface_oid_base + '.10'  # ifInOctets
    out_octets_oid = interface_oid_base + '.16'  # ifOutOctets
    while True:
        # Fetch input octets
        in_octets = next(getCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=0),
            UdpTransportTarget((target_ip, 161)),
            ContextData(),
            ObjectType(ObjectIdentity(in_octets_oid))
        ))[3][0][1]
        # Fetch output octets
        out_octets = next(getCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=0),
            UdpTransportTarget((target_ip, 161)),
            ContextData(),
            ObjectType(ObjectIdentity(out_octets_oid))
        ))[3][0][1]
        print(f"Interface In: {in_octets} bytes, Out: {out_octets} bytes")
        time.sleep(60)  # Poll every minute

# Example usage
poll_interface_stats('192.168.1.1', 'public', '1.3.6.1.2.1.2.2.1')

By capturing these metrics over time, network engineers can identify trends, detect anomalies, and perform capacity planning.

Monitoring CPU and Memory Usage

SNMP OIDs for CPU and memory vary across vendors, but standard MIBs like HOST-RESOURCES-MIB provide a common basis. For example, CPU load might be accessible via hrProcessorLoad (OID: 1.3.6.1.2.1.25.3.3.1.2), and memory utilization through hrStorageUsed (OID: 1.3.6.1.2.1.25.2.3). Polling these metrics periodically enables proactive management and automation of alerts for threshold breaches.

For comprehensive network monitoring, integrating polling scripts into dashboards or alert systems ensures prompt responses to issues, reducing downtime and maintaining optimal performance. Combining polling with Networkers Home Blog insights can guide the development of robust automation strategies.

SNMP SET — Changing Device Config via SNMP

While polling is common, SNMP also allows for device configuration changes through SET operations. This capability enables automation of network adjustments, such as toggling interface states, updating access control lists, or modifying device parameters.

Using pysnmp, an SNMP SET request involves specifying the OID and the new value, ensuring proper data types. For example, to enable an interface (OID: 1.3.6.1.2.1.2.2.1.7.2), you might set the value to 1 (up):

errorIndication, errorStatus, errorIndex, varBinds = next(setCmd(
    SnmpEngine(),
    CommunityData('private', mpModel=0),
    UdpTransportTarget(('192.168.1.1', 161)),
    ContextData(),
    ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.7.2'), Integer(1))
))
if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    print('Interface enabled successfully.')

Note that SNMP SET requires write access (using community string 'private' or equivalent) and appropriate permissions on the device. Misconfigured SET operations may disrupt network services; hence, they should be used carefully and tested thoroughly.

In practice, automating device configurations via SNMP SET enhances network management automation, enabling rapid response to network conditions or policy changes. It is advisable to maintain strict security controls and audit logs when performing SNMP SET operations, especially in production environments.

Handling SNMP Traps — Asynchronous Event Notifications

SNMP traps are unsolicited messages sent by network devices to notify administrators of specific events, such as link failures, high CPU load, or security breaches. Handling SNMP traps with Python involves setting up a trap receiver that listens for incoming trap messages asynchronously.

The pysnmp library supports trap receiving through its asynchronous SNMP engine. A typical trap handler involves binding a socket to a UDP port (usually 162) and processing incoming messages. Here’s an example:

from pysnmp.hlapi.asyncio import *
import asyncio

async def trap_receiver():
    def cb_fun(snmpEngine, stateReference, contextEngineId, contextName,
               varBinds, cbCtx):
        print('Received SNMP Trap:')
        for name, val in varBinds:
            print(f'{name.prettyPrint()} = {val.prettyPrint()}')
    snmpEngine = SnmpEngine()
    # Register UDP socket for traps
    transportDispatcher = AsyncioDispatcher()
    transportDispatcher.registerRecvCbFun(cb_fun)
    # Listen on default SNMP trap port
    transportDispatcher.registerTransport(
        udpDomain, UdpTransport().openServerMode(('0.0.0.0', 162))
    )
    print('Listening for SNMP traps...')
    await transportDispatcher.jobStarted(1)

# Run the trap listener
asyncio.run(trap_receiver())

This script sets up an asynchronous trap receiver that logs incoming trap data, enabling real-time alerting and automated response workflows. Deploying such a listener in a network management system ensures proactive detection of issues.

For effective trap handling, network devices must be configured to send traps to the monitoring server IP address and port. Proper filtering and parsing of trap data allow for targeted alerts and streamlined troubleshooting. This method complements polling strategies and forms the core of comprehensive network monitoring automation.

Storing SNMP Data — CSV, Database & Time-Series Options

Collected SNMP data needs to be stored efficiently for analysis, reporting, and historical trending. Depending on the scale and requirements, options include CSV files, relational databases, or specialized time-series databases.

CSV Files

For small-scale monitoring, exporting data to CSV provides a quick and easy solution. Python scripts can append data points with timestamps, facilitating manual review or integration with spreadsheet tools.

import csv
import datetime

def save_to_csv(data, filename='snmp_data.csv'):
    with open(filename, 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([datetime.datetime.now(), data['interface_in'], data['interface_out']])

# Example data dictionary
data = {'interface_in': 123456, 'interface_out': 654321}
save_to_csv(data)

Relational Databases

For larger deployments, storing SNMP data in databases like MySQL, PostgreSQL, or SQLite provides scalability and query capabilities. Python's SQLAlchemy or MySQL connector modules facilitate data insertion and retrieval.

Time-Series Databases

Specialized time-series databases such as InfluxDB or Prometheus are optimized for high-frequency metric storage and analysis. They support efficient querying, visualization, and alerting based on historical data, making them ideal for network monitoring automation.

Integrating SNMP poll data into these systems enables advanced analytics, trend visualization, and threshold-based alerts. Combining these storage options with dashboards like Grafana enhances network visibility, aligning with the goals of network automation courses at Networkers Home.

Building Custom Monitoring Scripts — Threshold Alerts & Reports

Automated monitoring scripts can be extended to include threshold checks, alert notifications, and report generation. For example, monitoring CPU usage and triggering an email alert if it exceeds 80% ensures timely response to potential issues.

Implementing Threshold Alerts

def check_cpu_threshold(cpu_value, threshold=80):
    if cpu_value > threshold:
        send_alert(f'CPU usage high: {cpu_value}%')
        
def send_alert(message):
    # Send email, SMS, or integrate with alerting platform
    print(f'ALERT: {message}')

# Usage in polling loop
cpu_load = get_cpu_usage()  # Assume this function fetches CPU load
check_cpu_threshold(cpu_load)

Generating Periodic Reports

Scripts can also generate summary reports over specified intervals, exporting data to PDF or email-friendly formats. This aids in regular review meetings and capacity planning.

Combining these capabilities empowers network administrators to maintain proactive oversight, reduce downtime, and improve overall network reliability. For comprehensive training on automation and scripting, explore courses offered at Networkers Home.

Practice: Monitor Interface Utilisation and Alert on Threshold

Practical application involves creating a Python script that continuously monitors interface utilization via SNMP, calculates utilization percentages, and sends alerts when thresholds are breached.

import time
from pysnmp.hlapi import *

def get_interface_octets(target_ip, community, interface_index):
    in_oid = f'1.3.6.1.2.1.2.2.1.10.{interface_index}'
    out_oid = f'1.3.6.1.2.1.2.2.1.16.{interface_index}'
    in_octets = next(getCmd(
        SnmpEngine(),
        CommunityData(community, mpModel=0),
        UdpTransportTarget((target_ip, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(in_oid))
    ))[3][0][1]
    out_octets = next(getCmd(
        SnmpEngine(),
        CommunityData(community, mpModel=0),
        UdpTransportTarget((target_ip, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(out_oid))
    ))[3][0][1]
    return int(in_octets), int(out_octets)

def monitor_interface(target_ip, community, interface_index, threshold=80):
    prev_in, prev_out = get_interface_octets(target_ip, community, interface_index)
    while True:
        time.sleep(60)
        curr_in, curr_out = get_interface_octets(target_ip, community, interface_index)
        in_speed = (curr_in - prev_in) * 8 / 60  # bits per second
        out_speed = (curr_out - prev_out) * 8 / 60
        utilization_in = (in_speed / 1e6) * 100  # assuming 1 Mbps link
        utilization_out = (out_speed / 1e6) * 100
        print(f'Interface {interface_index} In Utilization: {utilization_in:.2f}%, Out Utilization: {utilization_out:.2f}%')
        if utilization_in > threshold or utilization_out > threshold:
            print(f'Alert: Interface {interface_index} exceeds {threshold}% utilization!')
        prev_in, prev_out = curr_in, curr_out

# Example usage
monitor_interface('192.168.1.1', 'public', 2, threshold=80)

This script provides real-time monitoring and alerting on interface utilization, facilitating prompt troubleshooting and capacity planning. Implementing such scripts enhances network resilience and aligns with the automation skills taught at Networkers Home.

Key Takeaways

  • SNMP is essential for network monitoring, with multiple versions offering different security features.
  • pysnmp provides a powerful Python interface for SNMP GET, WALK, SET, and trap handling operations.
  • Automated polling of device metrics like interface stats, CPU, and memory enables proactive network management.
  • SNMP traps facilitate asynchronous alerts for critical network events, complementing polling strategies.
  • Storing SNMP data in CSV, databases, or time-series systems allows for detailed analysis and reporting.
  • Custom scripts with threshold-based alerts and report generation improve network reliability and visibility.
  • Practical exercises such as interface utilization monitoring demonstrate real-world application of SNMP Python monitoring.

Frequently Asked Questions

What are the security considerations when performing SNMP Python monitoring?

SNMPv1 and SNMPv2c use community strings that are often default and insecure, making them vulnerable to interception. SNMPv3 provides authentication and encryption, significantly improving security. Always disable default community strings, implement access controls, and restrict SNMP access to trusted IPs. Additionally, consider encrypting SNMP traffic using VPNs or secure tunnels for sensitive data. Regularly updating device firmware and monitoring SNMP logs further mitigate risks associated with SNMP monitoring activities.

How can I troubleshoot SNMP communication issues using Python scripts?

Begin by verifying network connectivity to the device IP and ensuring SNMP services are active. Use simple pysnmp GET commands to confirm correct community strings and OID access. Check firewall settings that might block UDP port 161. Enable SNMP debugging or verbose logging to trace message exchanges. Confirm device SNMP configurations, including access permissions. If issues persist, test with SNMP tools like snmpwalk or snmpget from the command line to isolate network or device problems, then adapt your Python scripts accordingly.

What are the best practices for automating network monitoring with Python and pysnmp?

Design scripts with modularity, allowing easy updates and maintenance. Use scheduling tools like cron or Windows Task Scheduler for periodic polling. Store collected data efficiently using databases or time-series platforms for scalability. Implement robust error handling and logging to detect and troubleshoot issues swiftly. Secure SNMP operations by using SNMPv3 where possible, and restrict access. Incorporate alerting mechanisms—emails, SMS, or integrations with monitoring dashboards. Regularly review and update scripts to adapt to network changes, ensuring continuous and reliable network monitoring automation at Networkers Home.

Ready to Master Python for Network Engineers?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and 100% placement support.

Explore Course