Quick start
Once you downloaded and installed PySNMP library on your Linux/Windows/macOS system, you should be able to solve the very basic SNMP task right from your Python prompt - fetch some data from a remote SNMP Agent (you’d need at least version 4.3.0 to run code from this page).
Fetch SNMP variable
So just cut&paste the following code right into your Python prompt. The code will performs SNMP GET operation for a sysDescr.0 object at a publically available SNMP Command Responder at demo.pysnmp.com:
import asyncio
from pysnmp.hlapi.asyncio.slim import Slim
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType
async def run():
slim = Slim(1)
errorIndication, errorStatus, errorIndex, varBinds = await slim.get(
'public',
'demo.pysnmp.com',
161,
ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print(
"{} at {}".format(
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
)
)
else:
for varBind in varBinds:
print(" = ".join([x.prettyPrint() for x in varBind]))
slim.close()
asyncio.run(run())
Download
script.
If everything works as it should you will get:
...
SNMPv2-MIB::sysDescr."0" = SunOS zeus.pysnmp.com 4.1.3_U1 1 sun4m
>>>
on your console.
Send SNMP TRAP
To send a trivial TRAP message to our hosted Notification Receiver at demo.pysnmp.com , just cut&paste the following code into your interactive Python session:
import asyncio
from pysnmp.hlapi.asyncio import *
async def run():
snmpEngine = SnmpEngine()
trap_result = await sendNotification(
snmpEngine,
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.pysnmp.com', 162)),
ContextData(),
"trap",
NotificationType(ObjectIdentity("1.3.6.1.6.3.1.1.5.2")).addVarBinds(
("1.3.6.1.6.3.1.1.4.3.0", "1.3.6.1.4.1.20408.4.1.1.2"),
("1.3.6.1.2.1.1.1.0", OctetString("my system")),
),
)
errorIndication, errorStatus, errorIndex, varBinds = await trap_result
if errorIndication:
print(errorIndication)
snmpEngine.transportDispatcher.closeDispatcher()
asyncio.run(run())
Download
script.
Many ASN.1 MIB files could be downloaded from mibs.pysnmp.com or PySNMP could be configured to download them automatically.
For more sophisticated examples and use cases please refer to examples and library reference pages.