python3 - TypeError:无法将字节连接到str

时间:2017-12-31 17:31:38

标签: python-3.5 elf

以下是代码:

def flip_bytes(binary_f):
    i = random.randint(0, len(binary_f))
    c = chr(random.randint(0, 0xFF))
    return binary_f[:i] + c + binary_f[i+1:]

def copy_binary():
    with open("license", "rb") as orig_f, open("license_fuzz", "wb") as fuzz_f:
        fuzz_f.write(flip_bytes(orig_f.read()))

license是一个ELF可执行文件,当我运行脚本时出现此错误:

Traceback (most recent call last):
  File "parse.py", line 30, in <module>
    copy_binary()
  File "parse.py", line 11, in copy_binary
    fuzz_f.write(flip_bytes(orig_f.read()))
  File "parse.py", line 7, in flip_bytes
    return binary_f[:i] + c + binary_f[i+1:]
TypeError: can't concat bytes to str

我该如何解决这个问题?

(以下是whole script以防万一)

1 个答案:

答案 0 :(得分:2)

变化:

c = chr(random.randint(0, 0xFF))

为:

c = bytes([random.randint(0, 0xFF)])

Python 3具有单独的字节和str类型。根据文档,bytes是bytearray的不可变版本:

https://docs.python.org/3.1/library/functions.html#bytes

https://docs.python.org/3.1/library/functions.html#bytearray

如果将数字传递给bytes / bytearray构造函数,它会将其解释为初始缓冲区大小而不是单个字节的初始值。这就是为什么你必须传递一个包含被解释为字节的数值的列表(它们必须为0-255,否则它将引发异常)。