如何用Python获取SNMP数据?

17 投票
1 回答
95096 浏览
提问于 2025-04-17 08:50

如何用Python从fdb表中获取MAC地址和VLAN信息?
在bash中,使用snmpwalk可以正常工作:

snmpwalk -v2c -c pub 192.168.0.100 1.3.6.1.2.1.17.7.1.2.2.1.2

使用pysnmp:

import os, sys
import socket
import random
from struct import pack, unpack
from datetime import datetime as dt

from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto.rfc1902 import Integer, IpAddress, OctetString

ip='192.168.0.100'
community='pub'
value=(1,3,6,1,2,1,17,7,1,2,2,1,2)

generator = cmdgen.CommandGenerator()
comm_data = cmdgen.CommunityData('server', community, 1) # 1 means version SNMP v2c
transport = cmdgen.UdpTransportTarget((ip, 161))

real_fun = getattr(generator, 'getCmd')
res = (errorIndication, errorStatus, errorIndex, varBinds)\
    = real_fun(comm_data, transport, value)

if not errorIndication is None  or errorStatus is True:
       print "Error: %s %s %s %s" % res
else:
       print "%s" % varBinds

输出结果:[(ObjectName(1.3.6.1.2.1.17.7.1.2.2.1.2), NoSuchInstance(''))]

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 = 2, DestHost='192.168.0.100',
                           Community='pub')
    return res

print getmac()

输出结果:('27', '27', '25', '27', '27', '27', '24', '27', '25', '18', '4', '27', '25', '27', '27', '25', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '23', '25', '27', '27', '27', '25', '27', '25', '27', '27', '25', '27', '27', '27', '27', '27', '27', '27', '27', '27', '25', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '25', '25', '25', '7', '27', '27', '9', '25', '27', '20', '19', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '11', '25', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '25', '27', '27', '27', '27', '27', '27', '27', '27', '27', '2', '27', '5', '27', '0', '27', '27', '27', '27', '27')

第一个脚本(pysnmp)返回了NoSuchInstance。第二个脚本(netsnmp)返回了一系列端口,但没有MAC和VLAN信息。到底出了什么问题?

1 个回答

15

在这个pysnmp的例子中,你正在进行的是SNMPGET(snmpget),而不是GETNEXT(snmpwalk)。如果你把

real_fun = getattr(generator, 'getCmd')

改成

real_fun = getattr(generator, 'nextCmd')

你就会开始看到有用的结果。

至于你在结果中看到的snmpwalk和python的net-snmp绑定之间的差异:snmpwalk和snmpbulkget的表现是不同的。如果你在命令行中用和snmpwalk相同的选项执行snmpbulkget,你会得到和你的python net-snmp例子一样的结果。

如果你在你的python net-snmp例子中更新以下这一行,

res = netsnmp.snmpgetbulk(oid, Version=2, DestHost='192.168.0.100', 
                          Community='pub')

改成

res = netsnmp.snmpwalk(oid, Version=2, DestHost='192.168.0.100', 
                       Community='pub')

那么你现在应该能从python net-snmp例子中得到和在命令行上执行snmpwalk时看到的相同结果列表。

撰写回答