如何使用pysnmp获取SNMP数据?

2024-04-19 00:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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数据?


Tags: 模块数据命令行命令ipaddressrespublic
1条回答
网友
1楼 · 发布于 2024-04-19 00:01:51

您似乎正在使用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调用更改为bulkCmdlike 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上使用它。

相关问题 更多 >