如何使用Python获取SNMP数据?

17

如何使用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', '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绑定结果之间看到的差异: snmpwalksnmpbulkget的行为不同。 如果您使用与snmpwalk相同的选项从命令行运行snmpbulkget,您将收到与您的python net-snmp 示例相同的结果。

如果您在python net-snmp示例中更新以下行,则会看到不同的结果:

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

to

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

如果一切顺利,您现在应该可以从Python的net-snmp示例中获得与命令行上执行snmpwalk时看到的相同结果列表。


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