2011-12-22 473 views
10

如何從fdb表中獲取value mac和vlan使用python?
在bash snmpwalk的工作精細: 如何從python獲取SNMP數據?

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','2 7', '27','27','27','27','27','2','27','5','27','0','27','27' ', '27','27','27')

冷杉腳本(pysnmp)返回NoSuchInstance。第二個腳本(netsnmp)返回端口但沒有mac和vlan的列表。什麼不對?

回答

8

在pysnmp示例中,您正在執行SNMPGET(snmpget),而不是GETNEXT(snmpwalk)。如果更改,

​​

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') 

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

那麼當你看到的時候,你現在應該得到蟒蛇net-snmp例子的結果相同的列表您在命令行上執行snmpwalk