Ad

How Can I Execute Terminal Commands From A C Program?

- 1 answer

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)

Ad

Answer

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:

[email protected]:/tmp$ gcc -Wall o.c
[email protected]:/tmp$ ./a.out date
samedi 11 avril 2020, 17:58:45 (UTC+0200)
[email protected]:/tmp$ a.out "date | wc"
      1       6      42
[email protected]:/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;
}
[email protected]:/tmp$ 
Ad
source: stackoverflow.com
Ad