我正在尝试编写具有许多 SNMP 事务的代码,一些事务可以捆绑getCmd()
到PySNMP
. 话虽如此,我不打算立即打印我的 SNMP 事务结果的值,有时需要进一步处理。IE:开箱。捆绑两个 SNMP 事务如下所示:
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('somePasswd'),
UdpTransportTarget(('somedev.example.com', 161)),
ContextData(),
#One MIB
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', '0')),
#Second MIB
ObjectType(ObjectIdentity('CISCO-CDP-MIB', 'cdpCacheAddress', 1,1)),
lookupNames=True,
lookupValues=True,
))
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
如果我想将特定 MIB 的值分配给变量,我看到它的方式是,我必须在我的最后一个 for 循环下放置一个 if..elseif 语句来比较我正在寻找的 MIB 的值到 oid 可迭代对象的当前值(我认为是术语)。所以,我的代码会像这样改变:
for oid, value in varBinds:
if oid == 'SNMPv2-MIB::sysName.0':
#take specific actions
elif oid == 'CISCO-CDP-MIB::cdpCacheAddress.1.1'
#take different actions
我认为这可能是一种做事方式,但是,我有几个问题:
这是处理多个 SNMP 事务的有效方式吗?
将每个 SNMP Get 事务分开是否会更好地提高代码的可读性?
当我执行以下操作时,我的 OID 将转换为对人类友好的 MIBS:
for varBind in varBinds print(' = '.join([x.prettyPrint() for x in varBind]))
但以下只是给我丑陋的oid:
for oid, value in varBinds:
print("oid:",oid,"Value",value):
通过将 oid 和 value 传递给我的 for 循环,我如何最终得到一个对人类友好的 mib 而不是丑陋的 oid?
更新:
像这样传递.loadMibs
给:在打印时仍然给了我一个 OID并且像这样:ObjectIdentity
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', '0').loadMibs('SNMPv2-MIB'))
oid
value
for oid, value in varBinds: