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?
randomir
18.8k1 gold badge46 silver badges60 bronze badges
1 Answer 1
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)
answered Nov 4, 2017 at 14:33
randomir
18.8k1 gold badge46 silver badges60 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
Joal
Forgot to mention, my disk image is 60+gb in size
Joal
How to i loop the first hex value (Currently 0xf) from x01 to xof ? >>> update = b'\x0f\x0a\xab\xcf\xfe\xfe'
randomir
Sorry, I don't understand your follow-up question.
Joal
i want to loop hex value x01 to x0f for only the first hex value AT variable " update = b'\x0f <<< this the first one ...................'"
randomir
I'm not sure I understand that. You want to insert 15 bytes
\x01...\x0f in a certain position in file? |
lang-py