Python Forum
Simple pysnmp example? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Simple pysnmp example? (/thread-44146.html)



Simple pysnmp example? - Calab - Mar-20-2025

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?


RE: Simple pysnmp example? - snippsat - Mar-20-2025

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.


RE: Simple pysnmp example? - Calab - Apr-14-2025

(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!