我想编写一个程序 Shellcode.c,它接受输入文本文件,其中包含由换行符分隔的 bash 命令,并执行文本文件中的每个命令:例如,文本文件将包含:
echo Hello World
mkdir goofy
ls
我尝试了这个(只是为了开始练习其中一个 exec 函数):
#include <stdio.h>
#include <unistd.h>
void main() {
char *name[3];
name[0] = "echo";
name[1] = "Hello World";
name[2] = NULL;
execvp("/bin/sh", name);
}
我得到,作为返回,
echo: Can't open Hello World
我被 execvp 函数卡住了,我哪里出错了?
最佳答案
你做错了。
第一个数组索引是程序的名称,如explained in the docs :
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.
此外,bash 不期望这样的自由格式参数,您需要告诉它您将使用 -c
选项传递命令:
所以,你需要:
name[0] = "sh";
name[1] = "-c";
name[2] = "echo hello world";
name[3] = NULL;
关于C - 使用 Execvp 执行 Bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141007/