如何使用pysnmp获取SNMP数据?

4

我希望使用Python的pysnmp模块获取SNMP数据。之前我一直是通过命令行获取SNMP数据,但现在想通过pysnmp模块来读取。

SNMP命令 -

snmpwalk -v 1 -c public <ip address>:<port> xyz::pqr

我之前使用的是如上所示的命令。现在我尝试了以下命令 -
import netsnmp

def getmac():
    oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.17.7.1.2.2.1.2'))
    res = netsnmp.snmpgetbulk(oid, Version = 1, DestHost='ip',
                           Community='pub')
    return res

print getmac()

我遇到了一个错误 - 导入netsnmp模块时出现“没有netsnmp模块” 有人可以给我建议吗?我如何使用Python从SNMP服务器获取SNMP数据?
1个回答

5
你似乎正在使用 netsnmp 模块而不是 pysnmp
如果你想使用 pysnmp,那么可以参考这个示例
from pysnmp.hlapi import *

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in nextCmd(SnmpEngine(),
                          CommunityData('public', mpModel=0),
                          UdpTransportTarget(('demo.snmplabs.com', 161)),
                          ContextData(),
                          ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))):
    if errorIndication or errorStatus:
        print(errorIndication or errorStatus)
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

更新:

以上循环将每次迭代获取一个OID值。如果您想更有效地获取数据,一种选择是将更多的OID填充到查询中(以许多ObjectType(...)参数的形式)。

或者,您可以切换到GETBULK PDU类型,方法是将您的nextCmd调用更改为bulkCmd像这样。

from pysnmp.hlapi import *

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in bulkCmd(SnmpEngine(),
        CommunityData('public'),
        UdpTransportTarget(('demo.snmplabs.com', 161)),
        ContextData(),
        0, 25,  # fetch up to 25 OIDs one-shot
        ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))):
    if errorIndication or errorStatus:
        print(errorIndication or errorStatus)
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

请记住,GETBULK命令支持最初是在SNMP v2c中引入的,因此您无法在SNMP v1上使用它。


谢谢您的回复。我尝试了您的代码片段,但是并没有检索到所有数据。您有什么想法,为什么会这样? - ketan
@IIya Etingof- 我们如何一次检索多个OID数据,比如10个? - ketan
@IIya Etingof- 如果我设置了多个ObjectType和多个OID,我将无法获取任何数据。我该如何利用GETBULK来实现呢?请给我一个示例片段。 - ketan
@kit 添加了 getbulk 代码片段。 - Ilya Etingof
@IIya Etingof- 谢谢。这就是我想要的。 - ketan
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接