libssh-多次发送请求并从通道读取应答

libssh - send request multiple times and read answer from channel

本文关键字:通道 读取 应答 请求 libssh-      更新时间:2023-10-16

我创建了一个会话和一个通道。大约每秒都会发送一个请求(ssh_channel_request_exec),我想读取该请求的答案(ssh_channel_read)。然而,我找不到关于如何发出多个请求的示例,api只包含一个关于如何发出请求、读取答案和关闭通道的示例。

当我尝试按顺序两次请求和读取通道时,ssh_channel_request_exec第二次返回错误。是否有必要为每个请求打开一个新的通道?

int ret = ssh_channel_request_exec(m_channel, request.c_str());
if (ret != SSH_OK)
{
    ssh_channel_close(m_channel);
    ssh_channel_free(m_channel);
    return false;
}
std::stringstream sstream;
nbytes = ssh_channel_read(m_channel, buffer, sizeof(buffer), 0);
while (nbytes > 0)
{
    sstream.write(buffer, nbytes);
    nbytes = ssh_channel_read(m_channel, buffer, sizeof(buffer), 0);
}
if (nbytes < 0) // 'nbytes' becomes zero the first time, the channel is not closed the second time!
{
    ssh_channel_close(m_channel);
    ssh_channel_free(m_channel);
    return false;
}
response = sstream.str();

该api还包含一个ssh_channel_send_eof函数,该函数在示例中从通道读取后使用。有什么好处?api只说"在通道上发送文件结尾。这不会关闭通道。你仍然可以从中读取,但不能写入。"

ssh_channel_is_eof的检查(api:"检查远程是否发送了EOF")显示通道不是第一次,而是第二次。

是。非交互式exec用于执行单个命令,因此您只能在单个通道中运行,如官方文档中所示。