pysnmp
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
- breaking Major API changes when migrating from `pysnmp4` to `pysnmp` (version 5.x and later). `pysnmp4` is a completely separate package and its API is incompatible with the modern `pysnmp` library.
- gotcha MIB (Management Information Base) loading and management can be complex, especially for custom or non-standard MIB files. Users often struggle with configuring `mibBuilder` correctly.
- gotcha pysnmp offers both synchronous and asynchronous (Twisted, asyncio) APIs. Mixing these or misunderstanding which API flavor is being used can lead to blocking issues in event-driven applications or unexpected behavior.
- gotcha The packaging structure for `pysnmp` (version 7.x) includes a dependency on `pysnmp-lextudio`, which can cause confusion. While `pysnmp-lextudio` is a required dependency, it often appears as a minimal, internal package.
Install
-
pip install pysnmp
Imports
- *
from pysnmp.hlapi import *
- SnmpEngine
from pysnmp.hlapi import SnmpEngine
- CommunityData
from pysnmp.hlapi import CommunityData
- UdpTransportTarget
from pysnmp.hlapi import UdpTransportTarget
- ContextData
from pysnmp.hlapi import ContextData
- ObjectType
from pysnmp.hlapi import ObjectType
- ObjectIdentity
from pysnmp.hlapi import ObjectIdentity
- cmdgen
from pysnmp.hlapi import getCmd
Quickstart
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}")