python modify binary file script

 1  Original File

 test.bin

 

2  Run Script

Modify One Byte,

 

result:

Modify One Word,

result:

 

Source Code:

#!/usr/bin/env python
import sys,os

if __name__ == '__main__':
    try:
        filename = sys.argv[1]
        offset = sys.argv[2]
        value = sys.argv[3]
        insert_type = sys.argv[4]
        print "input file size:", os.path.getsize(filename)
        if insert_type == 'B':
            print "insert Byte"
            print "offset: ", int(offset,0)
            pfile = open(filename,"rb+")
            pfile.seek(int(offset,0),0)
            print "value: ",int(value,0)
            pfile.write(chr(int(value,0)))
            pfile.flush()
            pfile.close()
        elif insert_type == 'W':
            print "insert Word"
            pfile = open(filename,"rb+")
            pfile.seek(int(offset,0)*4,0)
            pfile.write(chr(int("0x"+value[2:4],0)))
            pfile.write(chr(int("0x"+value[4:6],0)))
            pfile.write(chr(int("0x"+value[6:8],0)))
            pfile.write(chr(int("0x"+value[8:10],0)))
            pfile.flush()
            pfile.close()
    except:
        print("Error: run error.")
        pass

 

posted @ 2017-04-23 12:59  JustRelax  阅读(375)  评论(0编辑  收藏  举报