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

问题描述 投票:2回答:1

数小时以来,我一直在努力解决这个问题-希望有人能帮助我。我从程序的输出中解析出一个十六进制数,该输出是通过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\xfe\9a\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字符)后,bash中的“ hex_string”被用作“ \ x35 \ xfe \ 9a \ x30”。这不是问题,某些字符不可打印。

payload = '\x41\x41\x41' + hex_string
Output: AAA\x35\xfe\9a\x30

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

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

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

python type-conversion hex
1个回答
0
投票

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\xfe\9a\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'
© www.soinside.com 2019 - 2024. All rights reserved.