如何将十六进制编码的字符串转换为“人类可读的”字符串?

时间:2013-07-01 22:53:39

标签: python-2.7 hex net-snmp

我正在使用python的Net-SNMP绑定,我正试图从Brocade交换机中获取ARP缓存。这是我的代码的样子:

#!/usr/bin/env python

import netsnmp

def get_arp():
    oid = netsnmp.VarList(netsnmp.Varbind('ipNetToMediaPhysAddress'))
    res = netsnmp.snmpwalk(oid, Version=2, DestHost='10.0.1.243', Community='public')
    return res

arp_table = get_arp()

print arp_table

SNMP代码本身运行正常。 snmpwalk的输出如下所示:

<snip>
IP-MIB::ipNetToMediaPhysAddress.128.10.200.6.158 = STRING: 0:1b:ed:a3:ec:c1
IP-MIB::ipNetToMediaPhysAddress.129.10.200.6.162 = STRING: 0:1b:ed:a4:ac:c1
IP-MIB::ipNetToMediaPhysAddress.130.10.200.6.166 = STRING: 0:1b:ed:38:24:1
IP-MIB::ipNetToMediaPhysAddress.131.10.200.6.170 = STRING: 74:8e:f8:62:84:1
</snip>

但是我从python脚本输出的结果是一个十六进制编码的字符串元组,如下所示:

('\x00$8C\x98\xc1', '\x00\x1b\xed;_A', '\x00\x1b\xed\xb4\x8f\x81', '\x00$86\x15\x81', '\x00$8C\x98\x81', '\x00\x1b\xed\x9f\xadA', ...etc)

我花了一些时间谷歌搜索并遇到了struct模块和.decode("hex")字符串方法,但.decode("hex")方法似乎不起作用:

Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hexstring = '\x00$8C\x98\xc1'
>>> newstring = hexstring.decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found
>>>

struct的文档有点过头了。

2 个答案:

答案 0 :(得分:2)

更聪明的google-fu发现了这段代码片段,它给了我预期的结果:

def convertMac(octet):
    mac = [binascii.b2a_hex(x) for x in list(octet)]
    return ":".join(mac)

所以“解码”实际上是用词不当,因为此代码也会产生正确的结果(encodedecode似乎是binascii.a2b()binascii.b2a()的语法糖):

Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> string = '\x00$8\xa1\x1c2'
>>> string.encode("hex")
'002438a11c32'
>>>

答案 1 :(得分:1)

将Python的"hex"更改为"hex_codec"&lt; 3

这适用于python 3+可以使用?

>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)