C++:输出中不需要的字符

时间:2021-01-26 18:31:59

标签: c++ libssh

我正在使用 libssh,我想从执行的命令中获取一些输出。它在大多数情况下都有效,但我在输出中得到了不需要的字符。我做错了什么?

命令“test -f”/path/to/file“&& echo found || echo not found”的示例输出

not found
t foun

我想要“未找到”,而不是它下面的那一行——“t foun”

我认为问题出在哪里:

nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
while (nbytes > 0)
{
    output.append(buffer, sizeof(buffer));
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
}

这是我的函数。

std::string exec_command(ssh_session session, const std::string& command)
{
    ssh_channel channel;
    int rc;
    char* buffer;
    std::string output;
    int nbytes;

    channel = ssh_channel_new(ssh_session);
    if (channel == NULL)
        return "Error";

    rc = ssh_channel_open_session(channel);
    if (rc != SSH_OK)
    {
        ssh_channel_free(channel);
        return "Not Ok";
    }

    rc = ssh_channel_request_exec(channel, command.c_str());
    if (rc != SSH_OK)
    {
        ssh_channel_close(channel);
        ssh_channel_free(channel);
        return "Not Ok";
    }

    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes > 0)
    {
        output.append(buffer, sizeof(buffer));
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    }

    if (nbytes < 0)
    {
        ssh_channel_close(channel);
        ssh_channel_free(channel);
        return "Error";
    }

    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);

    return output;
}

1 个答案:

答案 0 :(得分:0)

sizeof(buffer) 表示 sizeof(char*),大概是 4 个字节。在 ssh_channel_read 中,第三个参数(计数)是缓冲区的限制。不是缓冲区中加载的元素数量。你得到它作为返回值。因此,首先,您需要为缓冲区分配一些内存,假设为 256 字节:

const int BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE];

现在您可以将缓冲区大小作为参数传递并填充缓冲区:

nbytes = ssh_channel_read(channel, buffer, BUFFER_SIZE, 0);
while (nbytes > 0)
{
    output.append(buffer, nbytes);
    nbytes = ssh_channel_read(channel, buffer, BUFFER_SIZE, 0);
}

并且您需要附加尽可能多的内容,即 nbytes

相关问题