Editing hex value at a particular position in disk image file using python

1.6k Views Asked by At

How do I edit hex value at a particular Sector of Disk image file (60GB) using Python?

Example:
Given 512,

File name: RAID.img
Typical File size: 60gb+
Sector: 3
Address Offset: 0000060A - 0000060F
Value: 0f, 0a , ab, cf, fe, fe

The code that I can think of:

fname = 'RAID.img'
with open(fname, 'r+b') as f:
    newdata = ('\x0f\x0a\xab\xcf\xfe\xfe')
    print newdata.encode('hex')

How do I modify data in Sector = 3, address is from 0000060A - 0000060F? Is there some library could use?

1

There are 1 best solutions below

7
randomir On BEST ANSWER

If you know the exact offset (byte position) of the data you want to update, you can use file.seek, followed by file.write:

#!/usr/bin/env python

offset = 0x60a
update = b'\x0f\x0a\xab\xcf\xfe\xfe'

with open('raid.img', 'r+b') as f:
    f.seek(offset)
    f.write(update)

If your data file is small (up to 1MB perhaps), you can read the complete binary file into a bytearray, play with (modify) the data in memory, then write it back to file:

#!/usr/bin/env python

offset = 0x60a
update = b'\x0f\x0a\xab\xcf\xfe\xfe'

with open('raid.img', 'r+b') as f:
    data = bytearray(f.read())
    data[offset:offset+len(update)] = update
    f.seek(0)
    f.write(data)