python 中的十六进制字符串类型转换

Hex string type conversion in python

几个小时以来,我一直在尝试解决这个问题 - 希望有人能帮助我。我从程序的输出中解析出一个十六进制数,我通过 Python 中的 Popen 运行。在下一步中,这个十六进制数用作通过 Popen 调用程序的另一个参数。问题是,我无法将十六进制值传递给 Popen,因此它可以工作:

cmd = "./my_program"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
response = p.stdout.read()
hexapattern = r'0x([0-9a-fA-F]+)'
hex_output = re.findall(hexapattern, str(response))[1]  #e.g.: hex_string = 35fe9a30
hex_string = '\x' + hex_output[6] + hex_output[7] + '\x' + hex_output[4] + hex_output[5] + '\x' + hex_output[2] + hex_output[3] + '\x' + hex_output[0] + hex_output[1]   #e.g.: hex_string = \x35\xfea\x30
payload = '\x41\x41\x41' + hex_string
cmd = "echo -e -n " + payload + " | ./my_program"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
response = p.stdout.read()
print(response)

下一行没有按应有的方式工作。虽然字符串的第一部分被正确解释(如 'AAA',编号为 41 的 ASCII 字符),但 'hex_string' 在 bash 中用作“\x35\xfea\x30”。这不是问题,有些字符不可打印。

payload = '\x41\x41\x41' + hex_string
Output: AAA\x35\xfea\x30

当我更改程序以手动将值设置为变量时(我不想这样做),它可以正常工作。

payload = '\x41\x41\x41' + '\x35\xfea\x30'
Output: AAA[not printable char][not printable char][not printable char]

我已经尝试了很多类型转换但都失败了。

ast.literal_eval 是一种使字符串看起来像按字面输入的方式。

hex_output = "35fe9a30"
hex_string = '\x' + hex_output[6] + hex_output[7] + '\x' + hex_output[4] + hex_output[5] + '\x' + hex_output[2] + hex_output[3] + '\x' + hex_output[0] + hex_output[1]   #e.g.: hex_string = \x35\xfea\x30
payload = '\x41\x41\x41' + hex_string

import ast

result =  ast.literal_eval('"{}"'.format(payload))

print('\x41\x41\x41' + '\x30\x9a\xfe\x35' == result)

打印 True(注意 hex_stringhex_output 的还原版本,它没有简化示例...)

我们刚刚告诉 ast.literal_eval 评估包含 payload

的字符串(因此用引号格式化)

codec 可能有更简单的解决方案,将整个数据处理为 bytes 而不是 str:

import codecs
print(b'\x41\x41\x41' + codecs.decode(hex_output.encode(),"hex"))

打印:

b'AAA5\xfe\x9a0'