【问题标题】:How to get SNMP data using pysnmp?如何使用 pysnmp 获取 SNMP 数据?
【发布时间】:2017-06-12 06:46:08
【问题描述】:

我想通过使用 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()

我遇到了错误 - import netsnmp.没有模块 netsnmp

谁能给我建议如何使用python从snmp服务器获取snmp数据?

【问题讨论】:

    标签: python snmp net-snmp pysnmp


    【解决方案1】:

    您似乎使用的是 netsnmp 模块,而不是 pysnmp

    如果您想使用pysnmp,那么this example 可能会有所帮助:

    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 like this 来完成。

    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 上使用它。

    【讨论】:

    • 感谢您的回复。我尝试了您的 sn-p,但未检索到所有数据。任何想法,为什么这样?
    • @IIya Etingof- 我们如何一次检索超过 10 个 OID 数据?
    • @kit 更新了我的答案,如果你需要的话请告诉我
    • @IIya Etingof- 如果我设置了多个具有多个 OID 的 ObjectType,我将得不到任何数据。我如何利用 GETBULK 来做到这一点。请给我样品 sn-p。
    • @kit 添加了 getbulk sn-p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多