使用 python 编辑磁盘映像文件中特定位置的十六进制值

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

如何使用 Python 编辑磁盘映像文件 (60GB) 的特定扇区的十六进制值?

Example:
Given 512,

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

我能想到的代码:

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

如何修改Sector = 3,地址为0000060A - 0000060F的数据? 有图书馆可以用吗?

如果您知道要更新的数据的准确偏移量(字节位置),您可以使用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)

如果您的数据文件很小(最多 1MB),您可以将完整的二进制文件读入 bytearray,使用(修改)内存中的数据,然后将其写回文件:

#!/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)