如何在Python中“开始”一个字节数组?

1 投票
1 回答
1250 浏览
提问于 2025-04-18 02:15

我知道“start”这个词用得不对,但我想你明白我想做什么……我知道有个叫“bytes”的函数,但我不知道怎么正确使用它。

比如我有这个字节数组:

'\x54\x68\x69\x73\x20\x70\x72\x6F\x67\x72\x61\x6D\x20\x6D\x75\x73\x74\x20\x62\x65'

我该怎么读取这个字节数组,并在Python脚本中使用它呢?我应该用什么函数,或者需要导入什么东西?谢谢你的回答(顺便说一下,我还是个新手)

1 个回答

0

这是你想的那个吗?

>>> bytes('\x54\x68\x69\x73\x20\x70\x72\x6F\x67\x72\x61\x6D\x20\x6D\x75\x73\x74\x20\x62\x65')                                              
'This program must be'
>>> 

如果你想在脚本中使用这个:

#!/usr/local/bin/python


# You can encode the python instructions on this webpage:
# http://www.string-functions.com/string-hex.aspx
#
#
# The following hex string encodes this:
# for i in xrage(0,10):
#     print i
thestring = "\x66\x6f\x72\x20\x69\x20\x69\x6e\x20\x78\x72\x61\x6e\x67\x65\x28\x30\x2c\x31\x30\x29\x3a\x0d\x0a\x20\x20\x20\x20\x70\x72\x69\x6e\x74\x20\x69"

# Demonstration of possible code injection
# in the function:
thehack = "import os;os.system('echo foobar')"


def hex2string(myhexstring):
    """be carefull with this function possible codeinjection"""
    myhexcmd = bytes("%s" % myhexstring)
    exec myhexcmd


hex2string(thestring)

祝好,

Dirk

撰写回答