C隐藏汇编程序中的文件

时间:2017-05-17 09:54:40

标签: c shell

我想在我的C代码中隐藏相同的文件(bash文件(文本))然后在运行时调用它atm我做这件事但它不好因为它不容易管理所有bash代码容易我想做某事比如bash1.sh,bash2.sh,bash3.sh ...在C代码中然后在代码中调用它而不使用#define因为它更容易在源代码上编辑.sh文件。

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
{
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;
}

2 个答案:

答案 0 :(得分:1)

InternetAussie已经很好地回答了C字符串文字部分。但是,它看起来并不比宏定义好,是吗?尝试将shell代码作为数组并连接字符串只会让你不必添加换行符,所以......

如果您能够尽可能轻松地修改shell脚本,如果您愿意为最初投入一些时间,那么请编写一个shell脚本转换器。

然后,您可以像通常一样编写shell脚本,最简单的方法是,如果shell脚本发生更改,让IDE在每次构建时使用翻译器生成C代码。

根据您的IDE,您可以安装预建任务,包括一些makefile或提供的任何内容。

生成的C代码将包含shell脚本作为定义(在您可以包含的头文件中)或全局字符串常量,就像在已经提到的答案中一样(在源文件中)。

示例解析器可能看起来像这样(不完整,你还需要动手;因为这是一个C问题,我提供C代码,但你可以使用其他任何合适的东西,比如perl):

#include <stdio.h>

char const* getCFileName(char const*)
{
    return 0; // replace .sh with .c?
}
char const* getVariableName(char const*)
{
    return 0; // find appropriate global variable name!
}

int main(int argc, char* argv[])
{
    if (argc < 2)
        return -1;
    FILE* in = fopen(argv[1], "r");
    if (!in)
        return -1;
    FILE* out = fopen(getCFileName(argv[1]), "w");
    if (!out)
    {
        fclose(in);
        return -1;
    }
    // filename possibly given in argv or derived from either argv1/2
    fprintf(out, "char const* const %s = \n", getVariableName(argv[1]));
    char buffer[1024];
    while (fgets(buffer, sizeof(buffer), in))
    {
        // escape special characters in buffer: '\', '"', ...
        // replace the terminating newline character with "\n", tabs with "\t", ...
        fprintf(out, "    \"%s\"\n", buffer);
    }
    fprintf(out, "%s", "    \"\";\n");
    // (included empty string for the case the file is empty - if so,
    //  generated C code still is valid...)

    fclose(in);
    fclose(out);

    return 0;
}

答案 1 :(得分:0)

根据Ped7g的建议,您可以使用base64之类的工具将脚本内容转换为in - Base64编码的字符串,以便它不包含任何字符需要在C字符串文字内转义。

请考虑以下示例脚本bash1.sh

#!/bin/bash
echo hello world

您可以通过base64

对其内容进行编码
base64 bash1.sh > bash1.base64

in-Base64编码的内容是:

cat bash1.base64
IyEvYmluL2Jhc2gKZWNobyBoZWxsbyB3b3JsZAo=

之后,您需要以某种方式“将此文件的内容放入C字符串”:

const char *bash1_64 = "IyEvYmluL2Jhc2gKZWNobyBoZWxsbyB3b3JsZAo=";

您可以使用以下Perl one-liner 来实现这一目标:

perl -lne 'print qq<const char * bash1_64 = "$_";>' bash1.base64 > bash1.h

之后,头文件bash1.h包含字符串bash1_64。您已经可以在源文件中包含此头文件。

上面显示的步骤可以收集和推广,例如,在 Makefile shell脚本中。

从现在开始,您必须决定如何解码包含要运行的脚本的字符串:

  1. 您可以解码此字符串的内容,然后再将其传递给system()
  2. 您可以创建一个由system()调用的常见 common shell脚本。此脚本将base64中编码的字符串作为参数,解码,然后运行其内容。通过将选项-d传递给base64程序,可以在shell脚本中轻松解码in-base64编码的字符串。