Bash脚本包含二进制可执行文件

Kat*_*ola 7 unix binary bash dump

是否可以编写一个包含二进制可执行程序的bash脚本?

我的意思是一个脚本,它包含一个文本形式的可执行文件的转储,当它被执行时将被这个脚本转储回可执行文件?

我很想知道一个解决方案,它可以开箱即用而无需安装额外的软件包.可能吗?

谢谢!

Zol*_*ich 6

我之前从未做过这样的事情;)这将编译一些c源代码,创建一个b.bash包含二进制文件的脚本(以及用于简单开发的原始脚本)

(惑)

#!/bin/bash

if [ "$0" == "b.bash" ];then
  tail -n +$[ `grep -n '^BINARY' $0|cut -d ':' -f 1` + 1 ] $0 | base64 -d > a2.out
  chmod +x a2.out
  ./a2.out
  echo $?
  exit
fi

cat "$0" > b.bash
echo "BINARY" >> b.bash
cat > a.c << EOF
int     main(){
        return 12;
}
EOF
gcc a.c 
base64 a.out >> b.bash
Run Code Online (Sandbox Code Playgroud)

调用(a.bash生成b.bash):

bash a.bash ;bash b.bash
Run Code Online (Sandbox Code Playgroud)

我不知道如何逃避在执行前将二进制文件写入临时文件...


sta*_*ark 5

我尝试了一下,效果很好。十六进制是用 xxd 生成的。

#!/bin/bash

xxd -r >foo <<'EndHere'
0000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 3e00 0100 0000 e003 4000 0000 0000  ..>.......@.....
0000020: 4000 0000 0000 0000 000a 0000 0000 0000  @...............
0000030: 0000 0000 4000 3800 0800 4000 1e00 1b00  ....@.8...@.....
0000040: 0600 0000 0500 0000 4000 0000 0000 0000  ........@.......
0000050: 4000 4000 0000 0000 4000 4000 0000 0000  @.@.....@.@.....
...
0001960: 6400 5f65 6461 7461 006d 6169 6e00 5f69  d._edata.main._i
0001970: 6e69 7400                                nit.
EndHere
chmod +x foo
./foo
Run Code Online (Sandbox Code Playgroud)

  • +1。不过,“base64”比“xxd”更适合。它更加紧凑。 (3认同)

jll*_*gre 5

不要像其他几个答案所建议的那样重新发明轮子,只需使用古老的shar命令,它正是通过设计来做到这一点的。

假设您要嵌入脚本的文件是binaryfile,只需运行

$ shar binaryfile > binaryfile.shar
Run Code Online (Sandbox Code Playgroud)

你已经准备好了。您有一个名为的 shell 脚本binaryfile.shar,执行时将提取binaryfile.

  • @erik你假设OP正在使用Gnu/Linux,但这没有说明。`base64` 并不比 `shar` 更符合 POSIX 标准,因此都不能保证在 Unix 平台上可用。 (3认同)
  • 但是您需要安装“sharutils”软件包,这不是默认的。`base64` 始终可用,因为它是 GNU coreutils 的一部分。 (2认同)