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
  • 17,989
  • 1
  • 40
  • 55
Joal
  • 19
  • 5

1 Answers1

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)
randomir
  • 17,989
  • 1
  • 40
  • 55
  • Forgot to mention, my disk image is 60+gb in size – Joal Nov 04 '17 at 14:34
  • How to i loop the first hex value (Currently 0xf) from x01 to xof ? >>> update = b'\x0f\x0a\xab\xcf\xfe\xfe' – Joal Nov 04 '17 at 14:45
  • Sorry, I don't understand your follow-up question. – randomir Nov 04 '17 at 14:48
  • i want to loop hex value x01 to x0f for only the first hex value AT variable " update = b'\x0f <<< this the first one ...................'" – Joal Nov 04 '17 at 14:54
  • I'm not sure I understand that. You want to insert 15 bytes `\x01...\x0f` in a certain position in file? – randomir Nov 04 '17 at 14:59
  • Given, update = b'\x0f\x0a\xab\xcf\xfe\xfe' . has 6 hex value. For the first hex value, i want to loop x01 all the way to 0xf . – Joal Nov 04 '17 at 15:03
  • Ok, so your question is how to generate a byte sequence with values of `\x01` to `\x0f`. Try this: `''.join(chr(i) for i in range(1,16))`. To append other bytes, just use the `+` operator. – randomir Nov 04 '17 at 15:10