0

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
asked Nov 4, 2017 at 14:18

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

7 Comments

Forgot to mention, my disk image is 60+gb in size
How to i loop the first hex value (Currently 0xf) from x01 to xof ? >>> update = b'\x0f\x0a\xab\xcf\xfe\xfe'
Sorry, I don't understand your follow-up question.
i want to loop hex value x01 to x0f for only the first hex value AT variable " update = b'\x0f <<< this the first one ...................'"
I'm not sure I understand that. You want to insert 15 bytes \x01...\x0f in a certain position in file?
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.