pipe(), fork(), exec(), ... providing input to and capturing output of a child process in C++

I am writing a C++ program, which should create a sub- process to start a telnet session to another server. Then it should login to that server (on the telnet login) and execute one or more command(s) on the remote server. The C++ program provides all the input for this process (username, password, servername, commands, ...) and should capture all the output returned by the telnet session process inside some variable. How can this be accomplished ? This is what I have so far, but since I'm not very good at working with pipes and children, I need the experts help on this one..

Thanks in advance.




#include <string>
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>

using namespace std;

int main(){

      string telnetString = "telnet";
      char* arguments[2];
      arguments[0] = "telnet";
      arguments[1] = "myserver.com";

      string loginname = "myLogin";
      string password = "mypass";
      string command = "ls -l > listing.txt"; // should create listing.txt on remote server (for testing only)

    ////
    // example of a possible real life series of commands :
   ////
  string command1 = "cd public_html";
  string command2 = "cat index.html"; // returns the output (= the contents of public_html/index.html on the remote server)
                                                       // back to the C++ program !!


      int fd2[2];
      int pipetest;

      pipetest = pipe(fd2);

      if(pipetest != 0) exit(1);
      else
      {
            // Pipe OK
            int pid;
            pid = fork();

            if(pid < 0) exit(2);

            if(pid == 0)
            { // child

                  ////
                  // NOT SURE ABOUT THIS PART !!
                  ////


                  ////
                  // Redirect childs input from parents output.
                  ////
                  //fd2[0] = 1;

                  close(fd2[1]);
                  dup2(fd2[0], 1);

                  ////
                  // Start the telnet program somehow
                  ////
                  execvp( telnetString.c_str() , arguments );
            }

            ////
            // Do the telnet (= child) login stuff
            // end execute the commands (just one for now)
            ////

            printf("%s\n", loginname.c_str());
            printf("%s\n", password.c_str());
            printf("%s\n", command.c_str());
            //printf("%s\n", command2.c_str());
            printf("exit\n"); // exit the telnet session

            ////
            // Find some way to capture the output of the telnet process
            // in this C++ program, to parse it later on.
            ////

      }

return 0;
};
LVL 1
HoegjeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

freewellCommented:
int main(int argc, char* argv[])
{
   char   psBuffer[128];
   FILE   *pPipe;
   char   psCommand[] = "dir *.c /on /p";

   if( (pPipe = _popen( psCommand, "rt" )) == NULL )
      exit( 1 );

   while( !feof( pPipe ) )
   {
      if( fgets( psBuffer, 128, pPipe ) != NULL )
         printf( psBuffer );
   }

   printf( "\nProcess returned %d\n", _pclose( pPipe ) );

   return 0;
}
0
jkrCommented:
You'd use 'pipe()' for that purpose:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main (int argc, char **argv)
{
  int filedes1[2], filedes2[2];
  int pid;
 
  /* Argument checking. */

  if (argc < 4)
    {
      puts("Wrong number of arguments given");
      exit(1);
    }

  /* Make our first pipe. */

  if (pipe(filedes1) == -1)
    {
      perror ("pipe");
      exit(1);
    }

  /* Make our second pipe. */
 
  if (pipe(filedes2) == -1)
    {
      perror ("pipe");
      exit(1);
    }

  /* Fork a child */

  if ((pid = fork()) == 0)
    {
      dup2(filedes1[0], fileno(stdin)); /* Copy the reading end of the pipe. */
      dup2(filedes2[1], fileno(stdout)); /* Copy the writing end of the pipe */
     
      /* Uncomment this if you want stderr sent too.

      dup2(filedes2[1], fileno(stderr));

      */

      /* If execl() returns at all, there was an error. */
     
      if (execl(argv[1], argv[1] == -1)) /* Bye bye! */
      {
        perror("execl");
        exit(128);
      }
    }
  else if (pid == -1)
    {
      perror("fork");
      exit(1);
    }
  else
    {
      int output;
      char c;

      write(filedes1[1], argv[2], strlen(argv[2])); /* Write the string */

      if((output = open(argv[3], O_WRONLY)) == -1)
      {
        perror("open");
        exit(1);
      }

      while (read(filedes2[0], &c, 1) != 0)
        write(output, &c, 1);
   
      exit(0);
    }
}
0
jkrCommented:
BTW, code taken from (and more info at) http://www.gmonline.demon.co.uk/cscene/CS4/CS4-06.html
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

HoegjeAuthor Commented:
I tried it, and the program skips all the child's code, because pid != 0. Wehn i am stepping through the program and I check pid every time, it changes from the uninitialised value to the parents pid value. So it does not start up any telnet session...

What next ?
0
jkrCommented:
>>I tried it, and the program skips all the child's code, because pid != 0

Yes, that is what the parent process is supposed to do. How are you calling the program?
0
jkrCommented:
BTW, found an error in the above code:

      if (execl(argv[1], argv[1] == -1)) /* Bye bye! */

should read

      if (execl(argv[1], argv[1]) == -1) /* Bye bye! */
0
HoegjeAuthor Commented:
Here is my code :

#include <string>
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>

using namespace std;

int main(){

      string telnetString = "telnet";
      char* arguments[2];
      arguments[0] = "telnet";
      arguments[1] = "myServer.com";

      string loginname = "myLogin";
      string password = "myPass";
      //string command = "cd public_html";
      string command = "ls -l > listing.txt";
      string command2 = "cat index.html";
      string strExit = "exit";


      int fd1[2];
      int fd2[2];
      int pipetest;
      int pid;

      pipetest = pipe(fd1);
      if(pipetest != 0) exit(1); // or ptest == -1

      pipetest = pipe(fd2);
      if(pipetest != 0) exit(1); // or ptest == -1
 
      {
            // Pipe OK
 

            if( (pid = fork()) == 0)
            { // child


                  ////
                  // Copy reading end of the pipe.
                  ////
 
                  dup2(fd1[0], fileno(stdin));

                  ////
                  // Copy writing end of the pipe.
                  ////

                  dup2(fd2[1], fileno(stdout));

                  close(fd2[1]);
                  dup2(fd2[0], 1);

                  ////
                  // Copy stderr too
                  ////
                  // dup2(fd2[1], fileno(stderr));

                  ////
                  // execute subprocess
                  // if it returns, there was an error
                  ////
                  execv( telnetString.c_str() , arguments );
            }
            else
            { // parent

                  int output;
                  char c;

                  ////
                  // Do the telnet (= child) login stuff
                  // end execute the commands (just one for now)
                  ////
                  write( fd1[1], loginname.c_str(), loginname.size() );
                  write( fd1[1], password.c_str(), password.size() );
                  write( fd1[1], command.c_str(), command.size() );
                  write( fd1[1], strExit.c_str(), strExit.size() );
                  write( fd1[1], strExit.c_str(), strExit.size() );

                  ////
                  // Find some way to capture the output of the telnet process
                  // in this C++ program, to parse it later on.
                  ////
/*                  while( read(fd2[0], &c, 1) != 0 ){
                        cerr << c;
                  }
                  exit(0);
*/
            }
      }

return 0;
};


What can I do ?
0
HoegjeAuthor Commented:
Does anybody know how I should access the child node ?
0
HoegjeAuthor Commented:
Ok, I found a solution myself, a bit of very low level code and stuff, but the important thing is I got it to work..
0
HoegjeAuthor Commented:
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <string>

using namespace std;

int ha_dados (FILE * fp, long ttl)
{
        fd_set rfd;
        struct timeval tv;
        int fd;

        tv.tv_usec = 0;
        tv.tv_sec = ttl;

        fd = fileno (fp);

        FD_ZERO (&rfd);
        FD_SET (fd, &rfd);

        return (select (fd + 1, &rfd, NULL, NULL, &tv));
}

int waitfor (FILE * fp, char * match, int print)
{
        int ch, x;

        x = 0;
        do {
                if (!ha_dados (fp, 10)) {
                        printf ("Timed out\n");
                        return (0);
                }

                ch = getc (fp);
                if (ch < 0) return 0;
                if (ch == match[x]) x++;
                if (print) putchar (ch);
        } while (match[x] != '\0');
        return (x);
}

int main (int argc, char **argv)
{
        FILE * out, * in;

      ////
      // Create a special FIFO file, similar to a named pipe
      ////
        mkfifo ("telnetMD.out", 0600);

        out = popen ("/bin/telnet swis.uia.ac.be 1>telnetMD.out 2>/dev/null", "w");
        if (!out) return (-1);

        in = fopen ("telnetMD.out", "r");
        if (!in) {
                fclose (out);
                return (-1);
        }

      ////
      // Make sure input and output is unbuffered
      ////
        setbuf (out, NULL);
        setbuf (in, NULL);

        if (waitfor (in, "login:", 0) == 0) {
                fclose (out);
                fclose (in);
                return (-1);
        }

        fprintf (out, "myLogin\n");

        if (waitfor (in, "Password: ", 0) == 0) {
                fclose (out);
                fclose (in);
                return (-1);
        }
        fprintf (out, "myPassword\n");

        if (waitfor (in, "$", 0) == 0) {
                printf ("Login failed\n");
                fclose (out);
                fclose (in);
                return (-1);
                return (-1);
        }

      fprintf (out, "cd public_htm\n");
      waitfor(in, "$", 1);

        fprintf (out, "ls -l\n");
        waitfor (in, "$", 1);

        fprintf (out, "exit\n");
        waitfor (in, ">", 0);

        fprintf (out, "exit\n");
        waitfor (in, "$", 0);


        fclose (out);
        fclose (in);

      system("rm telnetMD.out");

        return (0);
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.