首页 > 解决方案 > 如何返回从使用 PySNMP 完成的循环中获得的两个值?

问题描述

我是 PySNMP 和 Python 的新手,但对它充满热情。

我有一个取自 PySNMP 文档的脚本,我已经将它变成了一个名为 SnmpGetNext() 的 python 函数。

最后我想做的是从 nextCmd 获取两个 OID,这应该给我 1.3.6.1.2.1.2.2.1.14 .1 和 .2

当我这样做时,它会获取两个值并将其保存到字典中,这很棒。

for varBindTableRow in varBindTable:
    for name, val in varBindTableRow:
        result2 = {}

        result2['OID']= str(val)
        print(result2

但是我希望能够返回它们,然后使用此函数将其与更多 OID 一起使用,如果我返回 result2 这只会返回第一个值。

我尝试通过字典将 OID 传递给它,就像字符串一样。

from pysnmp.entity.rfc3413.oneliner import cmdgen

host = "demo.snmplabs.com"
community = "public"
test1 = ".1.3.6.1.2.1.2.2.1.14"

def SnmpGetNext(host,community,oid):
    errorIndication, errorStatus, errorIndex, \
                     varBindTable = cmdgen.CommandGenerator().nextCmd(
        cmdgen.CommunityData('test-agent', community),
        cmdgen.UdpTransportTarget((host, 161)),
        (oid),
        )

    if errorIndication:
        print (errorIndication)
    else:
        if errorStatus:
            print ('%s at %s\n' % (
                errorStatus.prettyPrint(),
                errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
                ))
        else:
            for varBindTableRow in varBindTable:
                for name, val in varBindTableRow:
                    result2 = {}

                    result2['OID']= str(val)
                    print(result2)
                    #return (name.prettyPrint(),val.prettyPrint())
                    #print ('%s = %s' % (name.prettyPrint(), val.prettyPrint()))


result = {}
result['test1']= SnmpGetNext(host,community,test1)
print(result)

期望的结果是通过运行

SnmpGetNext(host, community,test1) 获取:

1.3.6.1.2.1.2.2.1.14.1 1.3.6.1.2.1.2.2.1.14.2

标签: pythonpython-3.xpysnmp

解决方案


所以基本上我不得不使用而不是 return,yield,现在它工作得很好。


推荐阅读