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

标签 python unpack pysnmp octetstring

全部 - 我正在使用 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/

相关文章:

python - 无序复数浮点集的近似相等

android - Android 上与 Python 的套接字通信

php - 恢复解压 ('C*' , "string")

Python:读取 12 位二进制文​​件

python 值错误 : too many values to unpack in tuple

python - 使用 Python Asyncore 构建 SNMP 请求-响应服务

python - 将 NumPy 数组的第一维解压到 pyplot.plot 中

python - 在 Windows 上设置 Python simpleHTTPserver

python - PySNMP 错误 : pysnmp. smi.error.SmiError

python - PySNMP 查询接口(interface)的选择列表