简体   繁体   中英

How can I execute terminal commands from a C program?

I am creating a reverse shell in C (just for practice) and I don't know how to execute terminal commands from my C program. How should I go about doing this? (I am on a POSIX system) (I would like to get the output)

how to execute terminal commands from my C program... (I would like to get the output)

Look at popen

Example

#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <command>\n", *argv);
    return -1;
  }

  FILE * fp = popen(argv[1], "r");

  if (fp != 0) {
    char s[64];

    while (fgets(s, sizeof(s), fp) != NULL)
      fputs(s, stdout);

    pclose(fp);
  }

  return 0;
}

Compilation and executions:

bruno@bruno-XPS-8300:/tmp$ gcc -Wall o.c
bruno@bruno-XPS-8300:/tmp$ ./a.out date
samedi 11 avril 2020, 17:58:45 (UTC+0200)
bruno@bruno-XPS-8300:/tmp$ a.out "date | wc"
      1       6      42
bruno@bruno-XPS-8300:/tmp$ ./a.out "cat o.c"
#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <command>\n", *argv);
    return -1;
  }

  FILE * fp = popen(argv[1], "r");

  if (fp != 0) {
    char s[64];

    while (fgets(s, sizeof(s), fp) != NULL)
      fputs(s, stdout);

    pclose(fp);
  }

  return 0;
}
bruno@bruno-XPS-8300:/tmp$ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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