pysnmp

7.1.23 · active · verified Sat Apr 11

pysnmp is a robust, open-source Python library for implementing SNMP agents and managers. It provides comprehensive support for SNMP v1, v2c, and v3, including various transport mappings (UDP, TCP) and security models (USM, VACM). The library is currently at version 7.1.23 and follows a relatively active release cadence, addressing bug fixes and minor enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform a basic SNMP GET request using the high-level API (`pysnmp.hlapi`). It fetches a single OID (sysDescr.0 by default) from a specified host using a community string (SNMPv2c). The example handles potential error conditions returned by the SNMP agent.

import os
from pysnmp.hlapi import (
    SnmpEngine, CommunityData, UdpTransportTarget,
    ContextData, ObjectType, ObjectIdentity, getCmd
)

def snmp_get(host, community, oid):
    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=0), # mpModel=0 for SNMPv1, 1 for SNMPv2c
            UdpTransportTarget((host, 161)),
            ContextData(),
            ObjectType(ObjectIdentity(oid))
        )
    )

    if errorIndication:
        return f"Error: {errorIndication}"
    elif errorStatus:
        return f"Error: {errorStatus.prettyPrint()} at {varBinds[int(errorIndex)-1] if errorIndex else '?'}"
    else:
        return ', '.join([f'{x[0].prettyPrint()} = {x[1].prettyPrint()}' for x in varBinds])


# Example Usage:
# You can use a public SNMP demo server for testing, e.g., 'demo.snmplabs.com'
# Make sure to replace these with actual values for production environments
SNMP_HOST = os.environ.get('SNMP_HOST', 'demo.snmplabs.com')
SNMP_COMMUNITY = os.environ.get('SNMP_COMMUNITY', 'public')
# OID for sysDescr.0 (system description)
SNMP_OID = os.environ.get('SNMP_OID', '1.3.6.1.2.1.1.1.0')

if __name__ == '__main__':
    print(f"Attempting SNMP GET on {SNMP_HOST} for OID {SNMP_OID} with community '{SNMP_COMMUNITY}'")
    result = snmp_get(SNMP_HOST, SNMP_COMMUNITY, SNMP_OID)
    print(f"SNMP GET Result: {result}")

view raw JSON →