从libexpect获取输出

Get output from libexpect

本文关键字:输出 获取 libexpect      更新时间:2023-10-16

我正在尝试通过libexpect输入命令产生的输出,我不太擅长C风格的做事方式,我不确定如何继续。

问题是,虽然这是python用户的一个流行程序,但我只能找到一些在C/c++中使用libeexpect的基本示例,并且似乎没有提到获取输出。

示例程序:

// g++ t.cpp -lexpect -ltcl -o t
#include <iostream>
#include <tcl8.5/expect.h>
int main(){
    FILE *echo = exp_popen(const_cast<char *>("telnet google.com 80"));
    std::cout << char(fgetc(echo)) << std::endl;
    std::cout << std::string(80, '=') << std::endl;
    char c;
    do{
            c = fgetc(echo);
            std::cout << "'" << c << "'";
    }while(c != EOF);
    return 0;
}

虽然这部分工作,但它无法获得第一个字符。

实际上,SO在我发布正确答案后右侧显示了一个链接,我想我没有看得足够努力:

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

(取自如何从linux上c++中使用libeexpect创建的文件*中读取标准输出?)