首页 > 解决方案 > pysnmp 中的异步代码未按预期响应

问题描述

我是 pysnmp 库的新手。我尝试了 snmplabs 文档中提供的示例代码,并进行了某些修改,如下所示。

import asyncio
from pysnmp.hlapi.asyncio import *
@asyncio.coroutine
def run(host,oid):
    errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
        SnmpEngine(),
        CommunityData('public'),
        UdpTransportTarget((host, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(oid))
    )
    print(errorIndication, errorStatus, errorIndex, varBinds)


asyncio.get_event_loop().run_until_complete(run('demo.snmplabs.com','1.3.6.1.2.1.1.1.0'))
print("asynch_1")
asyncio.get_event_loop().run_until_complete(run('198.155.104.8','1.3.6.1.2.1.1.1.0'))
print("asynch_2")
asyncio.get_event_loop().run_until_complete(run('snmp.live.gambitcommunications.com','1.3.6.1.2.1.1.1.0'))
print("asynch_3")

在上面我尝试查询不同代理的 get-command。其中“198.155.104.8”是一个不存在的虚拟代理 ip。我希望出局

None 0 0 [ObjectType(ObjectIdentity(<ObjectName value object at 0x7fdaa071e400 tagSet <TagSet object at 0x7fdaa4760828 tags 0:0:6> payload [1.3.6.1.2.1.1.1.0]>), <DisplayString value object at 0x7fda9fcf8c88 tagSet <TagSet object at 0x7fdaa4760400 tags 0:0:4> subtypeSpec <ConstraintsIntersection object at 0x7fdaa085e7b8 consts <ValueSizeConstraint object at 0x7fdaa4710f28 consts 0, 65535>, <ValueSizeConstraint object at 0x7fdaa07a1fd0 consts 0, 255>, <ValueSizeConstraint object at 0x7fdaa085e780 consts 0, 255>> encoding iso-8859-1 payload [Linux zeus 4.8.6...11 CDT 2016 i686]>)]
asynch_1

None 0 0 [ObjectType(ObjectIdentity(<ObjectName value object at 0x7fda9fba2da0 tagSet <TagSet object at 0x7fdaa4760828 tags 0:0:6> payload [1.3.6.1.2.1.1.1.0]>), <DisplayString value object at 0x7fda9fbaa828 tagSet <TagSet object at 0x7fdaa4760400 tags 0:0:4> subtypeSpec <ConstraintsIntersection object at 0x7fda9fac1c88 consts <ValueSizeConstraint object at 0x7fdaa4710f28 consts 0, 65535>, <ValueSizeConstraint object at 0x7fda9f9e5cf8 consts 0, 255>, <ValueSizeConstraint object at 0x7fdaa36e4048 consts 0, 255>> encoding iso-8859-1 payload [Cisco Internetwo...5:14 by kellythw]>)]
asynch_3

No SNMP response received before timeout 0 0 []
asynch_2

由于没有代理引用“198.155.104.8”,因此代码不应在第二个请求中等待它应该打印第三个请求。

但我得到如下所示的输出


None 0 0 [ObjectType(ObjectIdentity(<ObjectName value object at 0x7fdaa071e400 tagSet <TagSet object at 0x7fdaa4760828 tags 0:0:6> payload [1.3.6.1.2.1.1.1.0]>), <DisplayString value object at 0x7fda9fcf8c88 tagSet <TagSet object at 0x7fdaa4760400 tags 0:0:4> subtypeSpec <ConstraintsIntersection object at 0x7fdaa085e7b8 consts <ValueSizeConstraint object at 0x7fdaa4710f28 consts 0, 65535>, <ValueSizeConstraint object at 0x7fdaa07a1fd0 consts 0, 255>, <ValueSizeConstraint object at 0x7fdaa085e780 consts 0, 255>> encoding iso-8859-1 payload [Linux zeus 4.8.6...11 CDT 2016 i686]>)]
asynch_1
No SNMP response received before timeout 0 0 []
asynch_2
None 0 0 [ObjectType(ObjectIdentity(<ObjectName value object at 0x7fda9fba2da0 tagSet <TagSet object at 0x7fdaa4760828 tags 0:0:6> payload [1.3.6.1.2.1.1.1.0]>), <DisplayString value object at 0x7fda9fbaa828 tagSet <TagSet object at 0x7fdaa4760400 tags 0:0:4> subtypeSpec <ConstraintsIntersection object at 0x7fda9fac1c88 consts <ValueSizeConstraint object at 0x7fdaa4710f28 consts 0, 65535>, <ValueSizeConstraint object at 0x7fda9f9e5cf8 consts 0, 255>, <ValueSizeConstraint object at 0x7fdaa36e4048 consts 0, 255>> encoding iso-8859-1 payload [Cisco Internetwo...5:14 by kellythw]>)]
asynch_3

因为我是snmp的新手。我无法通过使用异步代码一次查询多个代理的解决方案。

请帮助理解问题。如果以错误的方式编写代码,请纠正我的代码。

任何帮助都将是可观的。

提前致谢

标签: pythonpython-asyncionet-snmppysnmp

解决方案


这个答案将阐明为什么会run_until_complete()阻止您的代码执行。

简而言之,您必须为循环创建一个任务列表(couroutines),然后完全异步运行它。

使用现代 async / await 语法(Python 3.5+),您重构的代码将如下所示:

import asyncio
from pysnmp.hlapi.asyncio import *

async def run(host,oid):
    errorIndication, errorStatus, errorIndex, varBinds = await getCmd(
        SnmpEngine(),
        CommunityData('public'),
        UdpTransportTarget((host, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(oid))
    )
    print(errorIndication, errorStatus, errorIndex, varBinds)

async def main():
    tasks = []
    tasks.append(run('demo.snmplabs.com','1.3.6.1.2.1.1.1.0'))
    tasks.append(run('198.155.104.8','1.3.6.1.2.1.1.1.0'))
    tasks.append(run('snmp.live.gambitcommunications.com','1.3.6.1.2.1.1.1.0'))
    results = await asyncio.gather(*tasks)

if __name__ == '__main__':
    asyncio.run(main())

请看一下Ilya Etingof @ github 的这个例子

附带说明:最好在脚本/线程中保留一个可重用的 SnmpEngine 对象。这个对象的初始化成本很高,它拥有各种缓存,因此重新创建它会大大降低 pysnmp 的速度。(с) etingof

该建议大大提高了性能(约快 3 倍)。下面是另一个版本的代码,带有额外的错误处理并返回可读的结果。

import asyncio
import pysnmp.hlapi.asyncio as snmp

async def get(host,oid):
    result = []
    try:
        snmp_engine = snmp.SnmpEngine()
        response = await snmp.getCmd(snmp_engine,
                                     snmp.CommunityData('public'),
                                     snmp.UdpTransportTarget((host, 161)),
                                     snmp.ContextData(),
                                     snmp.ObjectType(snmp.ObjectIdentity(oid)))

        errorIndication, errorStatus, errorIndex, varBinds = response

        if errorIndication:                
            print(f'{host}: errorIndication: {errorIndication}')
        elif errorStatus:
            print('{}: {} at {}'.format(host, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        else:
            for varBind in varBinds:
                result.append([x.prettyPrint() for x in varBind])

        snmp_engine.transportDispatcher.closeDispatcher()

    except Exception as err:
        print (f'Error at SNMP get() due to {err}')

    finally:
        print(f'Get {host}, {oid}: {result}')
        return result

async def main():
    tasks = []
    tasks.append(get('demo.snmplabs.com','1.3.6.1.2.1.1.1.0'))
    tasks.append(get('198.155.104.8','1.3.6.1.2.1.1.1.0'))
    tasks.append(get('snmp.live.gambitcommunications.com','1.3.6.1.2.1.1.1.0'))
    results = await asyncio.gather(*tasks)
    print(f'main() results: {results}')

if __name__ == '__main__':
    asyncio.run(main())

有关 asyncio 的更多理解,请参阅以下教程:

最好的祝愿。


推荐阅读