gpt4 book ai didi

python - 如何使用 python 从 SNMP 获取数据?

转载 作者:太空狗 更新时间:2023-10-29 17:18:22 24 4
gpt4 key购买 nike

如何从fdb表中获取值mac和vlan使用python?
在 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

output: [(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()

output: ('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。怎么了?

最佳答案

在 pysnmp 示例中,您正在执行 SNMPGET (snmpget),而不是 GETNEXT (snmpwalk)。如果你改变了,

real_fun = getattr(generator, 'getCmd')

real_fun = getattr(generator, 'nextCmd')

您将开始看到有用的结果。

至于您在 snmpwalk 和 python net-snmp 绑定(bind)结果中看到的差异: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')

然后您现在应该从 python net-snmp 示例中获得相同的结果列表,就像您在命令行上执行 snmpwalk 时看到的一样。

关于python - 如何使用 python 从 SNMP 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8601324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com