首页 > 解决方案 > 我的语法 read().encode("hex") 在 python 3 中不起作用

问题描述

def run_action(self):
     if os.path.exists(self.vars["source"][0]):
         self.ui.print_msg("Shellcode:")
         print ("\\x" + "\\x".join(re.findall("..", open(self.vars["source"][0], "rb").read().encode("hex"))))
     else:
         self.ui.print_error("%s not found" % self.vars["source"][0])

这是该功能不适用于 Python3:

print ("\\x" + "\\x".join(re.findall("..", open(self.vars["source"][0], "rb").read().encode("hex"))))

我在上面的行中遇到错误。你能帮我按照python3语法写这个函数吗?

标签: python-3.xpython-3.6python-3.7

解决方案


看起来您想将字节字符串打印为十六进制转义码。Python 3 不再支持.encode('hex'),但在 Python 2 和 3 中有更好的方法来实现这一点:

蟒蛇 2.7:

>>> data = 'data'
>>> print(''.join(['\\x{:02x}'.format(ord(b)) for b in data]))
\x64\x61\x74\x61

Python 3.6+:

>>> data = b'data'
>>> print(''.join([f'\\x{b:02x}' for b in data]))
\x64\x61\x74\x61

推荐阅读