在有限的linux中编辑hex / binary文件

时间:2015-02-12 15:50:51

标签: linux awk sed binary hex-editors

我有一个非常有限的linux w /几个基本的linux命令。 我需要在十六进制/二进制文件中替换几个字符:

INPUT:

# hexdump -C block.bin
00000000  11 11 50 04 42 00 00 00  58 00 00 00 3c 0e e2 d4  |..P.B...X...<...|
00000010  50 0b 00 00 00 80 00 00  00 00 00 00 00 00 d0 d7  |P...............|
00000020  1f 09 00 00 00 00 02 00  00 00 00 04 ff ff ff ff  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000040  28 31 98 5b d3 0e 05 00  00 00 00 00 00 00 00 00  |(1.[............|
00000050  00 00 00 00 00 00 00 00  64 00 00 00 00 00 10 00  |........d.......|
00000060  00 ff ff ff ff 00 00 00  00 03 01 0d 03 01 0d 01  |................|
00000070  00 00 00 00 0c 00 01 02  00 00 00 00 00 ff ff ff  |................|
00000080  ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
*
00000180  00 00 20 00 00 00 ff ff  ff ff 01 00 00 0c 00 00  |.. .............|
00000190  04 00 00 00 02 00 00 04  00 00 00 00 00 00 ff ff  |................|
000001a0  ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
*
00000200  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|

我需要更改以下内容:

00000060  00 ff ff ff ff 00 00 00  00 03 01 0d 03 01 0d 01  |................|
00000070  00 00 00 00 0c 00 01 02  00 00 00 00 00 ff ff ff  |................|

to(并重写回同一个文件):

00000060  00 ff ff ff ff 00 00 00  00 03 01 0d 03 01 0d 02  |................|
00000070  01 00 00 00 0c 00 01 02  00 00 00 00 00 ff ff ff  |................|

就像我说的,我有一些命令:hexdump,od,vi,nano,awk,sed,python。 通过互联网查看,许多解决方案需要第三方安装或使用'xxd'。我都不能用。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

我不认为尝试使用sed或awk这是一个理智的想法,所以我们一直坚持使用python,这对于这项任务来说肯定足够强大。我正在思考这些问题:

#!/usr/bin/python

# open file in binary mode for reading and writing    
f = open("block.bin", "r+b")

# seek to position and read two bytes
f.seek(0x6f)
data = f.read(2)

# seek to position again
f.seek(0x6f)

# and write the transformed characters back
for d in data:
    f.write(chr(ord(d) + 1))

f.close()