Python Netsnmp 和 snmpwalk

Python Netsnmp and snmpwalk

我正在尝试使用 snmpwalk 在某些界面上获取一些信息和统计信息。我用这个:

import netsnmp

serv = "172.16.1.1"
snmp_pass = "private"

oid = netsnmp.VarList('IF-MIB::ifName','IF-MIB::ifDescr')
snmp_res = netsnmp.snmpwalk(oid, Version=2, DestHost=serv, Community=snmp_pass)
for x in snmp_res:
    print "snmp_res:: ", x

我得到的答案是:

snmp_res:: lo
snmp_res:: EtherNet Adapter XYZ

答案正确,但我需要更多信息。当我用 snmpwalk 从 linux 命令做同样的事情时,我得到更多信息,例如:

IF-MIB::ifDescr.1 = STRING: lo
IF-MIB::ifDescr.2 = STRING: EtherNet Adapter XYZ

"EtherNet Adapter XYZ" 的 ID 为 2,我也需要该值作为界面上其他统计信息的参考。如何使用 python 和 snmp 获得 that/them?

直接从 the documentation:

snmpwalk(<Varbind/VarList>, <Session args>))

Takes args of netsnmp.Session preceded by a Varbind or VarList from which the 'walk' operation will start. Returns a tuple of values retrieved from the MIB below the Varbind passed in. If a VarList is passed in it will be updated to contain a complete set of VarBinds created for the results of the walk. It is not recommended to pass in just a Varbind since you loose the ability to examine the returned OIDs. But, if only a Varbind is passed in it will be returned unaltered.

Note that only one varbind should be contained in the VarList passed in. The code is structured to maybe handle this is the the future, but right now walking multiple trees at once is not yet supported and will produce insufficient results.

您已经传递了一个 VarList,所以您已经拥有了您需要的东西。您只需要正确检查结果即可。

The tests举个例子:

vars = netsnmp.VarList(netsnmp.Varbind('system'))

vals = sess.walk(vars)
print "v1 sess.walk result: ", vals, "\n"

for var in vars:
    print "  ",var.tag, var.iid, "=", var.val, '(',var.type,')'

关键是修改了input变量,给你所需要的。 return值对你来说没有多大价值(笑)

将这些放在一起看起来您想要以下内容:

import netsnmp

serv = "172.16.1.1"
snmp_pass = "private"

oid = netsnmp.VarList('IF-MIB::ifName','IF-MIB::ifDescr')
snmp_res = netsnmp.snmpwalk(oid, Version=2, DestHost=serv, Community=snmp_pass)
for x in oid:
    print "snmp_res:: ", x.iid, " = ", x.val

(免责声明:无法测试;根据需要进行调整)

该文档中有足够的关于 VarBindVarList 的信息,可以从 x 中找出最好的东西.

但是,

x.iid 是实例标识符,所以它应该为您提供您所追求的 12。不过,也不要忘记检查 x.tag,它将是 IF-MIB::ifNameIF-MIB::ifDescr(或等效的东西;您必须进行试验)。