python - 如何在 PySNMP 中进行单个 GETNEXT 查询

标签 python pysnmp

我正在尝试创建一个简单的 snmp GETNEXT 查询来检索树层次结构中给定 OID 的下一项。

例如,我想要的是:

当我使用 OID 1.3.6.1.2.1.1 (iso.org.dod.internet.mgmt. mib-2.system)

我希望得到一个单一响应,包括 OID 1.3.6.1.2.1.1.1.0 (iso.org.dod.internet .mgmt.mib-2.system.sysDescr.0) 及其相应的值。

事实是:

PySNMP 不再检索单个下一个值,而是在 1.3.6.1.2.1.1 下执行 SNMP 遍历并检索所有子项。

如何更改此行为并使其仅返回单个下一个值而不是执行 snmpwalk?

我使用以下代码,该代码取自 PySNMP 文档。

# GETNEXT Command Generator
from pysnmp.entity.rfc3413.oneliner import cmdgen

errorIndication, errorStatus, errorIndex, \
                 varBindTable = cmdgen.CommandGenerator().nextCmd(
    cmdgen.CommunityData('test-agent', 'public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    (1,3,6,1,2,1,1)
    )

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:
                print '%s = %s' % (name.prettyPrint(), val.prettyPrint())

最佳答案

@Cankut,pysnmp 的“oneliner”GETNEXT API 的工作原理是检索给定前缀下的所有 OID 或直到 mib 结尾的所有 OID。

执行您想要的操作的一种方法是将 pysnmp 的股票响应处理函数替换为您自己的(这还需要使用较低级别的异步 API):

from pysnmp.entity.rfc3413.oneliner import cmdgen

def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
        return 1
    if errorStatus:
        print(errorStatus.prettyPrint())
        return 1
    for varBindRow in varBindTable:
        for oid, val in varBindRow:
            print('%s = %s' % (oid.prettyPrint(),
                               val and val.prettyPrint() or '?'))

cmdGen  = cmdgen.AsynCommandGenerator()

cmdGen.nextCmd(
    cmdgen.CommunityData('test-agent', 'public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    ((1,3,6,1,2,1,1),),
    (cbFun, None)
)

cmdGen.snmpEngine.transportDispatcher.runDispatcher()

关于python - 如何在 PySNMP 中进行单个 GETNEXT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8643047/

相关文章:

python - 为什么 async pysnmp 这么慢?

python - 在使用 NumPy 时理解 randn 的最小值和最大值

python - 如何使用字典替换 Pandas 系列中的多个子字符串?

python - 通过名称访问另一个模块中的变量

python - 如何在 pysnmp 中查找 mib 表?

python - 异步 getNext 超出表时出错

python - pysnmp 示例程序中的 asyncio "Task was destroyed but it is pending!"

python - google-app-engine 全文搜索,哪个更好, "google custom search"或 whoosh

python - 似乎无法让 fortran 可执行文件通过 python 正确运行