优势

优势

我正在寻找一种将可执行​​二进制文件硬连线到脚本中的方法。像这样的东西:

#!/bin/bash
...some shell code
execute binary:
    >>>
        binary
        code
        ...
    <<<
...some more shell code possibly

我发现了这个解决方案,使用uuencode和 是好的。但这取决于shrutils,这似乎是一个额外的,因为它们默认不包含在我的 Debian 中。

我一直在考虑对二进制文件进行编码base64,然后对其进行解码不知何故执行,可能不会创建任何临时文件。我记得有一个库负责执行事情,但忘记了它是什么。

最好有一个像这样执行的简单构造:

$ <(base64 out | base64 -d)
bash: /dev/fd/63: Permission denied

答案1

怎么样:

unpack() {
    tail +9 "$0" > /tmp/xxx.$$
    chmod +x /tmp/xxx.$$
}
unpack
/tmp/xxx.$$ <add args here>
rm /tmp/xxx.$$
exit
<add the binary here>

如果您不喜欢脚本中包含二进制数据,您可以对其进行编码并替换cat为相关的解码器。

+9请注意,如果您将脚本修改为不同的长度,则需要将 替换为二进制文件开始的行号。

如果您的tail实现不支持该参数+9,请尝试-n +9改为。

如果您担心破坏现有的 /tmp 文件,请尝试使用mktemp(1)创建 tmp 文件名。

请注意,此方法由编译器套件的升级脚本使用SunPro,其中包括带有整个升级的压缩 tar 存档和一些用于管理围绕该升级的处理的 shell 代码。

答案2

从...开始

aShellScript aBinaryExecutable

zip binary.zip aBinaryExecutable
cat aShellScript binary.zip > hybrid
chmod +x hybrid

我错过了在脚本中放入什么来提取和运行二进制文件,但请注意hybrid是一个有效的 zip 文件和一个有效的 shell 脚本,shell 脚本可以解压缩自身并获取二进制可执行文件(但不是 shell脚本)。

优势

稳健:该文件是有效的 zip 和有效的 shell 脚本(只要您在尝试解释最后的垃圾之前退出)。

坏处

剧本的结尾很难看。

为什么它有效

  • shell从文件开头开始解释。 (所有偏移量都是象征性的。)
  • zip从文件末尾开始解释。所有偏移都是相对的。

答案3

我会在脚本末尾添加一个标记标签。我们假设“ONLY_BINARY_AFTER_THIS_POINT:”是我的标记。您的脚本可以包含这些行。

#!/usr/bin/env bash
# my_script.sh


# find the line number where my tag is in this file
line_number=$(grep -na -m1 "^ONLY_BINARY_AFTER_THIS_POINT:$" "$0"|cut -d':' -f1)
# next line is where contents of my binary file starts, use mathematical expansion to increase it by 1
$((line_number+=1))
# dump everything after $line_number of this script into somewhere I can access
tail -n +"${line_number}" "$0" > /tmp/my_binary_file.bin
# do further processing on /tmp/my_binary_file.bin


# don't forget the new line here and don't type in anything after this point
#                            ↓
ONLY_BINARY_AFTER_THIS_POINT:

然后你可以将二进制文件附加到你的脚本中

cat my_script.sh my_binary_file.bin > my_appended_script.sh

重要的是你应该只有一个新行,并且没有其他的在将二进制文件附加到脚本之前。此外,如果您在附加后编辑脚本,则应谨慎选择文本编辑器。保存脚本时,文本编辑器可能会更改一些字符。

笔记:您还可以直接附加到脚本,但如果添加重定向“>”,而不是附加“>>”,您的脚本将被覆盖。

相关内容