如何从linux上用libexpect在c++中创建的FILE*中读取标准输出

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

本文关键字:创建 FILE 标准输出 读取 c++ linux 上用 libexpect      更新时间:2023-10-16

使用c++创建了一个FILE*,使用libeexpect:

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

我进入命令行使用:

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

现在在bash shell中,我想获得一个文件的内容,所以我必须运行命令cat /port1/port并获得它在字符缓冲区中打印的所有内容。我怎么做呢?

fgets似乎不工作…

Thanks in advance

假设您的机器和"sunblaze"处于一个防火墙隔离的、相当安全的环境中,我将使用"ssh-keygen"answers"ssh-copy-id root@sunblaze"来允许您的用户ID无需密码即可登录到sunblaze。这样,你的代码中就不会有别人可以看到的密码。

是的,我知道,这不是你想要的…

我真的不明白为什么fgets(str, size, fd); -我将有一个小游戏来弄清楚…

#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;
}

但是,如果ssh的输出没有换行符,显然,fgets()不会完成。当我第一次尝试的时候,它在一个密码问题上卡住了——但是当我把它改成一台不需要密码就可以登录的机器时,它工作得很好。

找到了一种方法,在按我所做的方式创建连接后,shell是:

[root@sanblaze ~]#

我给它写一个命令,例如:

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

使用grep:

读取文件内容
fputs("cat /port4/port | grep -w Moder" , fp);
exp_fexpectl(fp, exp_exact , "]# " , 1 , exp_end);

完成上述操作后,"exp_buffer"巫婆是一个全局变量,它保存上次"exp_fexpectl"运行时来自远程shell的所有文本,巫婆只表示我的命令的输出。剩下的就是解析它了。