如何在shell脚本中修改二进制文件?

时间:2022-09-16 14:40:03

Is there have any command to modify binary file in shell?

shell中是否有修改二进制文件的命令?

First i created a file with all 0xff value

首先,我创建了一个具有所有0xff值的文件。

 $ dd if=/dev/zero ibs=1K count=1 | tr "\000" "\377" > ./Test.img
 $ hexdump Test.img
   0000000 ffff ffff ffff ffff ffff ffff ffff ffff
   *
   0000400

Then i wanted to change some byte value like

然后我想要改变一些字节值,比如

   0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff
   *
   0000400

How can i change that? or any command in shell script?

我怎么才能改变呢?还是shell脚本中的命令?

Thanks

谢谢

2 个解决方案

#1


2  

Using python

Python was designed to be binary-clean, so here is one approach:

Python被设计成二进制清洁,所以这里有一种方法:

$ python -c 'open("New.img", "wb").write( "\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc" + open("Test.img", "rb").read()[10:] )'

Here is the resulting file:

这里是结果文件:

$ hexdump New.img
0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff
0000010 ffff ffff ffff ffff ffff ffff ffff ffff
*
0000400

Using shell

The shell is not binary-clean. For example, no shell string can contain the character \x00. Consequently, any approach using shell may be subject to unpleasant surprises. However, if one must, try:

壳体不是二进制清洁的。例如,没有shell字符串可以包含字符\x00。因此,任何使用shell的方法都可能会遇到令人不快的意外。但是,如果一定要这样做,那就试试:

LC_ALL=C; { printf "%s" $'\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc'; tail -c+11 New.img; } >New2.img

#2


1  

you can just vim -b bin-file-name, this would start vim in binary mode, which allows you to do anything to any file, as long as you know what you are doing.

您可以只是vim -b bin-file-name,这将在二进制模式下启动vim,这允许您对任何文件执行任何操作,只要您知道自己在做什么。

#1


2  

Using python

Python was designed to be binary-clean, so here is one approach:

Python被设计成二进制清洁,所以这里有一种方法:

$ python -c 'open("New.img", "wb").write( "\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc" + open("Test.img", "rb").read()[10:] )'

Here is the resulting file:

这里是结果文件:

$ hexdump New.img
0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff
0000010 ffff ffff ffff ffff ffff ffff ffff ffff
*
0000400

Using shell

The shell is not binary-clean. For example, no shell string can contain the character \x00. Consequently, any approach using shell may be subject to unpleasant surprises. However, if one must, try:

壳体不是二进制清洁的。例如,没有shell字符串可以包含字符\x00。因此,任何使用shell的方法都可能会遇到令人不快的意外。但是,如果一定要这样做,那就试试:

LC_ALL=C; { printf "%s" $'\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc'; tail -c+11 New.img; } >New2.img

#2


1  

you can just vim -b bin-file-name, this would start vim in binary mode, which allows you to do anything to any file, as long as you know what you are doing.

您可以只是vim -b bin-file-name,这将在二进制模式下启动vim,这允许您对任何文件执行任何操作,只要您知道自己在做什么。