使用 bash 编辑可执行文件而不重新编译它?

Edit an executable with bash without recompiling it?

我正在尝试以这种方式编写用于编辑可执行文件(例如 /bin/bash)的脚本:

搜索字符串 - 用新字符串替换旧字符串 - 保存对原始文件的更改(显然,出于安全原因,我正在尝试 /bin/bash 的副本)

我的字符串是一个单词。我该怎么做?

您可以使用 sed 轻松修改二进制文件中的字符串,但是 在评论中指出,它通常只在新旧字符串长度相同时才有效。以 bash 为例:

$ cp /bin/bash .
$ strings bash  | grep such
describe_pid: %ld: no such pid
    it creates, on systems that allow such control.
          such as cd which change the current directory.
%s: no such job
$ sed 's,no such job,no such boj,' -i bash
$ ./bash --noprofile --norc
bash-4.3$ kill %3333
bash: kill: %3333: no such boj

-i 对于 sed 而不是 POSIX 所以如果你想实现最大的便携性:

$ cp /bin/bash .
$ sed 's,no such job,no such boj,' bash > bash.bak
$ mv bash.bak bash
$ chmod +x ./bash
$ ./bash --noprofile --norc
bash-4.3$ kill %3333
bash: kill: %3333: no such boj