-1

我有以下 Python 脚本,我想使用 setuid/setgid 位提供的权限执行:

#!/usr/bin/env python3
from mypackage.cli import main as cli_main
cli_main()

但是:我想直接从 C 包装器执行命令,而不需要中间的 Python 脚本文件。

我尝试使用execve如下方式执行此操作:

#include <stdlib.h>
#include <string.h>
#include <unistd.h>

const char *ENV = "/usr/bin/env";
const char *ENV_ARGS[] = { "python3", "-c", "from mypackage.cli import main as cli_main; cli_main()" };
const int NUM_ENV_ARGS = 3;

int main(int argc, char *argv[], char *envp[]) {
    int total_num_args = (argc - 1) + NUM_ENV_ARGS + 1;

    // Create an array of strings to hold the final arg list.
    // No need to free the malloc'ed memory as it will be freed if execve succeeds,
    // or when the program exits if execve fails.
    char **final_args = (char **)malloc(total_num_args * sizeof(char *));
    if (final_args == NULL) {
        return 1;
    }

    // Copy the invocation and the arguments to this program into the final arg list.
    memcpy(final_args, ENV_ARGS, NUM_ENV_ARGS * sizeof(char *));
    memcpy(final_args + NUM_ENV_ARGS, argv + 1, (argc - 1) * sizeof(char *));
    final_args[total_num_args - 1] = NULL;

    return execve(ENV, final_args, envp);
}

但是当我运行编译的程序时出现以下错误./mycli foo bar

python3: illegal option -- c
usage: env [-iv] [-P utilpath] [-S string] [-u name]
           [name=value ...] [utility [argument ...]]

我怎样才能做到这一点?

4

2 回答 2

1

你没有运行python3命令。你正在运行env命令。该ENV变量应包含/usr/bin/python3,或您要访问的任何python3内容。

于 2016-12-05T20:29:56.920 回答
1

您正在错误地构造参数数组。它应该与执行程序的数组完全对应argv,包括第 0元素指定程序的名称,在这种情况下通常是“env”或“/usr/bin/env”。因为您跳过了“env”,env所以将“python3”解释为它自己的名称,如错误消息所示。该消息来自env,而不是来自 Python。

于 2016-12-05T20:37:44.823 回答