在C语言中,可以使用system()
函数来运行shell脚本。然而,直接将用户输入的参数传递给system()
函数可能存在安全风险,因为用户可以通过参数注入任意命令。
以下是一个安全地从C语言运行带有参数的shell脚本的方法,工作示例:
#include
#include
#include
int main(int argc, char *argv[]) {
char command[1000] = "sh script.sh "; // 假设shell脚本为script.sh
// 检查参数个数
if (argc < 2) {
printf("请提供参数!\n");
return 1;
}
// 将参数拼接到命令中
for (int i = 1; i < argc; i++) {
strcat(command, argv[i]);
strcat(command, " ");
}
// 运行命令
system(command);
return 0;
}
在以上代码中,我们将用户输入的参数拼接到一个命令字符串中,并使用system()
函数来运行该命令。通过使用strcat()
函数来拼接参数可以避免参数注入的安全风险。
要使用以上代码示例,你需要创建一个名为script.sh
的shell脚本,并将需要执行的命令写入该脚本中。然后,编译并运行C程序,将shell脚本的路径作为第一个参数,其他参数作为后续参数传递给脚本。
示例运行命令:./program /path/to/script.sh arg1 arg2 arg3
这将安全地运行带有参数的shell脚本。