使用 C++,我使用 libexpect 创建了一个 FILE*:
FILE* fd = exp_popen("ssh root@sunblaze");
我使用以下命令进入命令行:
exp_fexpectl(fp , exp_exact , "password: " , 1 , exp_end);
现在其他人在 bash shell 中,我想在那里获取文件的内容,
所以我必须运行命令 cat/port1/port
并在字符缓冲区中获取它打印的所有内容。
我该怎么做?
fgets
似乎不起作用...
提前致谢
最佳答案
假设您的计算机和“sunblaze”处于防火墙关闭、相当安全的环境中,我将使用“ssh-keygen”和“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() 将无法完成。当我第一次尝试时,它陷入了密码问题 - 但当我将其更改为无需密码即可登录的机器时,它工作得很好。
关于c++ - 如何在 Linux 上从 C++ 中使用 libexpect 创建的 FILE* 读取标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056481/