Skip to content

Commit

Permalink
Expanded sample code to show asyncio usage.
Browse files Browse the repository at this point in the history
  • Loading branch information
lextm committed Sep 15, 2024
1 parent d8ca7e7 commit 8bcf8a0
Showing 1 changed file with 45 additions and 35 deletions.
80 changes: 45 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,53 +87,63 @@ PySNMP is designed in a layered fashion. Top-level and easiest to use API is kno

```python
from pysnmp.hlapi.v1arch.asyncio import *
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType

with Slim(1) as slim:
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 "?",
)
import asyncio


async def run():
with Slim(1) as slim:
errorIndication, errorStatus, errorIndex, varBinds = await slim.get(
'public',
'demo.pysnmp.com',
161,
ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
)
else:
for varBind in varBinds:
print(" = ".join([x.prettyPrint() for x in varBind]))

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]))

asyncio.run(run())
```

This is how to send SNMP TRAP:

```python
from pysnmp.hlapi.v3arch.asyncio import *

import asyncio


async def run():
snmpEngine = SnmpEngine()
errorIndication, errorStatus, errorIndex, varBinds = await sendNotification(
snmpEngine,
CommunityData('public', mpModel=0),
await UdpTransportTarget.create(('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")),
),
)

snmpEngine = SnmpEngine()
errorIndication, errorStatus, errorIndex, varBinds = await sendNotification(
snmpEngine,
CommunityData('public', mpModel=0),
await UdpTransportTarget.create(('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")),
),
)
if errorIndication:
print(errorIndication)

if errorIndication:
print(errorIndication)
snmpEngine.closeDispatcher()

snmpEngine.closeDispatcher()
asyncio.run(run())
```

> We maintain publicly available SNMP Agent and TRAP sink at
Expand Down

0 comments on commit 8bcf8a0

Please sign in to comment.