简体   繁体   English

在c程序中执行Linux命令

[英]Execute a Linux command in the c program

I am trying to execute a Linux command in c program using system system call, but the don't want it to dump the output or error logs on the terminal.我正在尝试使用系统系统调用在 c 程序中执行 Linux 命令,但不希望它在终端上转储输出或错误日志。 What should I do?我该怎么办? Is there any other way to do this?有没有其他方法可以做到这一点?

由于 system() 调用使用 shell 来执行命令,因此您可以将 stdout 和 stderr 重定向到 /dev/null,例如

system("ls -lh >/dev/null 2>&1");

popen is another way in which you can do the same: popen是您可以执行相同操作的另一种方式:

void get_popen() {
    FILE *pf;
    char command[20];
    char data[512];

    // Execute a process listing
    sprintf(command, "ps aux wwwf"); 

    // Setup our pipe for reading and execute our command.
    pf = popen(command,"r"); 

    // Error handling

    // Get the data from the process execution
    fgets(data, 512 , pf);

    // the data is now in 'data'

    if (pclose(pf) != 0)
        fprintf(stderr," Error: Failed to close command stream \n");

    return;
}

Show you code.给你看代码。

Try for example:尝试例如:

system("ls");系统(“ls”);

The system() and popen() calls start a shell and pass their arguments to it, which creates security vulnerabilities. system()popen()调用启动一个 shell 并将它们的参数传递给它,这会产生安全漏洞。 Unless all parts of the arguments originating from user input are correctly sanitized according to the shell's quoting and escaping rules, an attacker can probably run arbitrary commands on the system.除非根据 shell 的引用和转义规则对源自用户输入的所有参数部分进行正确清理,否则攻击者可能会在系统上运行任意命令。

Instead, use the exec family of commands.相反,请使用exec命令系列。 These start the command directly, without starting a shell.这些直接启动命令,无需启动 shell。 You may still need to sanitize the input, but only to limit what may be passed to the command itself.您可能仍然需要清理输入,但只是为了限制可能传递给命令本身的内容。

Example from the SEI CERT C Coding Standard :来自SEI CERT C 编码标准的示例:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
  
void func(char *input) {
  pid_t pid;
  int status;
  pid_t ret;
  char *const args[3] = {"any_exe", input, NULL};
  char **env;
  extern char **environ;
 
  /* ... Sanitize arguments ... */
 
  pid = fork();
  if (pid == -1) {
    /* Handle error */
  } else if (pid != 0) {
    while ((ret = waitpid(pid, &status, 0)) == -1) {
      if (errno != EINTR) {
        /* Handle error */
        break;
      }
    }
    if ((ret == 0) ||
        !(WIFEXITED(status) && !WEXITSTATUS(status))) {
      /* Report unexpected child status */
    }
  } else {
    /* ... Initialize env as a sanitized copy of environ ... */
    if (execve("/usr/bin/any_cmd", args, env) == -1) {
      /* Handle error */
      _Exit(127);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM