Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple pysnmp example?
#1
I'm running python 3.13. I have v 7.1.17 of the pysnmp module installed.

I'm trying to do a simple SNMP get, but I am having trouble understanding how pysnmp works. The examples I find online are out of date, don't work, or are confusing for me.

This is my code:
from pysnmp.hlapi.v3arch import *

community_string = 'mystring'
host = 'my_host'

x = get_cmd(SnmpEngine(),
           CommunityData(community_string),
           UdpTransportTarget.create((host, 161)),
           ContextData(),
           ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0')),   # SysName
           lookupMib=False,
           lexicographicMode=False,
           )
           
print(next(x))
When run, I get the following error when I try to print(next(x)):
TypeError: 'coroutine' object is not an iterator

Can someone explain why this is, or better yet, provide a very simple SNMP get example using pysnmp?
Reply
#2
The error occurs because in version 7.x of pysnmp the API has changed to use asynchronous coroutines rather than returning a synchronous iterator.
In your code, calling next(x) on a coroutine is causing the error since you need to await it.
Try this:
import asyncio
from pysnmp.hlapi.v3arch import *

community_string = 'mystring'
host = 'my_host'

async def snmp_get():
    result = await get_cmd(
        SnmpEngine(),
        CommunityData(community_string),
        UdpTransportTarget.create((host, 161)),
        ContextData(),
        ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0')),  # SysName
        lookupMib=False,
        lexicographicMode=False,
    )
    return result

if __name__ == '__main__':
    response = asyncio.run(snmp_get())
    print(response)
Asynchronous API in pysnmp 7.x,the functions get_cmd return a coroutine.
This means that instead of using next() on a synchronous iterator, you must await the coroutine to get the result.
asyncio.run() to execute it,this is the standard way to run asyncio asynchronous code in Python.
Calab likes this post
Reply
#3
(Mar-20-2025, 04:44 PM)snippsat Wrote: The error occurs because in version 7.x of pysnmp the API has changed to use asynchronous coroutines rather than returning a synchronous iterator.

Thanks! That code was quite helpful!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to know coming snmp trap version in python pysnmp? ilknurg 0 3,605 Jan-31-2022, 12:16 PM
Last Post: ilknurg

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020