All -我正在使用python和pysnmp通过snmp收集思科发现协议数据。因为我使用的是CDP,所以我使用的是CISCO-CDP-MIB.my,我面临的问题是如何解压cdpCacheCapabilities和cdpCacheAddressType的内容。我见过许多示例,并在我的代码中尝试过它们,但它们对我的特定场景没有帮助。请帮助我理解解包背后的原则,以便我不仅可以将它们应用于我正在工作的两个MIB,还可以应用于其他MIB,这些MIB也可能以打包格式返回数据。cdpCacheCapabilities的结果应该类似于"00000040",我尽可能地打印出结果,但是"0x“总是在我的值之前,我只需要这个值,没有符号。cdpCacheAddress的结果应该是十六进制表示法的IP地址。对于cdpCacheAddress,我需要首先解压内容,从而留下一个十六进制字符串,然后将其转换为IP地址,即"192.168.1.10“。请解释你的答案背后的逻辑,以便我可以在其他情况下调整它。谢谢
from pysnmp.hlapi import *
from pysnmp import debug
import binascii
import struct
#use specific flags or 'all' for full debugging
#debug.setLogger(debug.Debug('dsp', 'msgproc'))
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in nextCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('10.1.1.1', 161)),
ContextData(),
ObjectType(ObjectIdentity('CISCO-CDP-MIB', 'cdpCacheCapabilities')),
lookupNames=True,
lookupValues=True,
lexicographicMode=False):
if errorIndication:
print(errorIndication)
break
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
break
else:
for varBind in varBinds:
value = varBind[-1]
arg = value.prettyPrint()
print(arg)
#dec = format(value,'x')
#dec = repr(value)
dec = struct.unpack('c',value)
print(dec)发布于 2018-08-12 00:22:19
通过启用MIB查找,您要求pysnmp使用MIB将SNMP变量绑定对(OID和值)转换为对人类友好的东西。
如果只需要无格式的裸值,并且假设这两个托管对象的类型为OCTET STRING,则可以对该值调用.asOctets()或.asNumbers()方法,以获得原始str|bytes或int的序列
for oid, value in varBinds:
raw_string = value.asOctets()
raw_ints = value.asNumbers()编辑:
一旦你有了原始值,你就可以将它们转换成任何东西:
>>> ''.join(['%.2x' % x for x in b'\x00\x00\x04\x90'])
'00000490'
>>>
>>> '.'.join(['%d' % x for x in (10,0,1,202)])
'10.0.1.202'https://stackoverflow.com/questions/51800328
复制相似问题