1

我正在使用 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有点让我头疼。

4

2 回答 2

2

一些更聪明的 google-fu 发现了这个代码片段,这给了我期望的结果:

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

所以“解码”确实是用词不当,因为这段代码也产生了正确的结果(encodeanddecode似乎是binascii.a2b()and的语法糖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'
>>>
于 2013-07-01T23:19:30.250 回答
1

更改"hex""hex_codec"Python < 3

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

>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)
于 2013-07-01T23:02:22.340 回答