How to read stdout from a FILE* created with libexpect in C++ on linux?

不问归期 提交于 2020-01-16 08:23:09

问题


Using C++ I created a FILE* using libexpect:

FILE* fd = exp_popen("ssh root@sunblaze");

I got to the command line using:

exp_fexpectl(fp , exp_exact , "password: " , 1 , exp_end);

Now the other posses in bash shell and I want to get the contents of a file there, so I have to run the command cat /port1/port and get all it prints in a char buffer. How do I do that?

fgets doesn't seem to work...

Thanks in advance


回答1:


Assuming that your machine and "sunblaze" are within a firewalled off, reasonably secure environment, I would use "ssh-keygen" and "ssh-copy-id root@sunblaze" to allow your user ID to log in to sunblaze without a password. That way, you don't have a password in your code that someone can look at.

Yes, I know, this wasn't what you were asking...

I don't actually see why fgets(str, size, fd); - I will have a little play to figure out...

This definitely works:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tcl8.5/expect.h>
#include <errno.h>

int main()
{
    char str[512];
    FILE *f = exp_popen("ssh user@mybox ls -lR");
    if (f==NULL)
    {
        printf("Failed (%s)\n", strerror(errno));
        return 1;
    }
    while(fgets(str, sizeof(str)-1, f))
    {
        printf("%s", str);
    }
    return 0;
}

However, if the output from ssh doesn't have a newline, obviously, fgets() won't complete. When I first tried, it got stuck on a password question - but when I changed it to a machine that I can log in to without a password, it worked fine.




回答2:


found a way, after creating the connection the way i did, the shell is:

[root@sanblaze ~]#

i write a command to it using for example:

fputs("echo LinkReset > /port4/port\r" , fp);
exp_fexpectl(fp, exp_exact , "]# " , 1 , exp_end);

reading a files content with grep:

fputs("cat /port4/port | grep -w Mode\r" , fp);
exp_fexpectl(fp, exp_exact , "]# " , 1 , exp_end);

after doing the above the "exp_buffer" witch is a global variable holds all the text that came from the remote shell from the last time "exp_fexpectl" ran, witch means only the output of my command. all that's left is to parse it.



来源:https://stackoverflow.com/questions/14056481/how-to-read-stdout-from-a-file-created-with-libexpect-in-c-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!