如何从linux上用libexpect在c++中创建的FILE*中读取标准输出
How to read stdout from a FILE* created with libexpect in C++ on linux?
使用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的所有文本,巫婆只表示我的命令的输出。剩下的就是解析它了。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- Seg Fault Issue C++ (file IO / getline)
- 使用CMake创建QML插件
- make 命令创建 .file,但不创建应用程序文件
- fopen 在创建大量文件后因 EFBIG "File too large" 而失败
- 如何在"Microsoft Visual Studio Community 2015"的现有"C++ Project"中创建新"header file (.h)"?
- QT 创建器:无法添加 OpenCV dll 库 ( "File format not recognized" )
- 从 FILE* 指针创建流对象
- AR 无法创建存档:"File format not recognized"
- 是否可以在内存中创建一个C FILE对象来读/写?
- 创建新文件时,它显示"<SFML/Graphics.hpp> no such file or directory"
- 在 cpp、OpenCV 中使用"Select file"对话框创建 GUI
- 具有异常路径(如"C:\test\\file.txt"含义)的创建文件(...)
- 从字符串创建FILE*
- 协同创建实例失败,并显示错误"System can not find the file specified"
- 如何创建一个继承FILE方法的类
- 获取一个FILE *句柄而不实际在磁盘上创建一个文件
- 如何从linux上用libexpect在c++中创建的FILE*中读取标准输出