gpt4 book ai didi

python - 将 OctetString 数据解包到变量中以进行进一步处理

转载 作者:行者123 更新时间:2023-12-01 09:09:18 25 4
gpt4 key购买 nike

全部 - 我正在使用 python 和 pysnmp 通过 snmp 收集思科发现协议(protocol)数据。由于我与 CDP 合作,因此我使用 CISCO-CDP-MIB.my我面临的问题是解压 cdpCacheCapability 和 cdpCacheAddressType 的内容。我看过很多例子并在我的代码中尝试过它们,但它们对我的特定场景没有帮助。请帮助我理解解包背后的原理,以便我不仅可以将它们应用于我正在使用的两个 MIB,还可以应用于其他也可能以打包格式返回数据的 MIB。 cdpCacheCapability 的结果应该类似于“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)

最佳答案

通过启用 MIB 查找,您要求 pysnmp 使用 MIB 将 SNMP 变量绑定(bind)对(OID 和值)转换为人类友好的内容。

如果您只需要裸露的、非格式化的值,并假设这两个托管对象的类型是OCTET STRING,则可以调用.asOctets().asNumbers() 方法对值进行获取原始 str|bytesint 序列:

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'

关于python - 将 OctetString 数据解包到变量中以进行进一步处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800328/

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