我正在尝试从远程服务器获取命令“ df”的输出,稍后将替换该命令:

#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    ssh_session my_ssh_session;
    int rc;
    ssh_channel channel;
    char buffer[256];
    int nbytes;
    int port = 22;
    my_ssh_session = ssh_new();


    if (my_ssh_session == NULL)
    exit(-1);
    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "192.168.2.2");
    ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);

    rc = ssh_connect(my_ssh_session);

    if (rc != SSH_OK)
            {
            fprintf(stderr, "Failed %s\n",
            ssh_get_error(my_ssh_session));
            exit(-1);
            }



    channel = ssh_channel_new(my_ssh_session);
    if (channel == NULL)
    return SSH_ERROR;

    rc = ssh_channel_open_session(channel);
    if (rc != SSH_OK)
            {
            ssh_channel_free(channel);
            return rc;
            }
    rc = ssh_channel_request_exec(channel, "df");
    if (rc != SSH_OK)
            {
            ssh_channel_close(channel);
            ssh_channel_free(channel);
            return rc;
            }
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes > 0)
            {
            if (write(1, buffer, nbytes) != nbytes)
                    {
                    ssh_channel_close(channel);
                    ssh_channel_free(channel);
                    return SSH_ERROR;
                    }
            nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
            }
    if (nbytes < 0)
            {
            ssh_channel_close(channel);
            ssh_channel_free(channel);
            return SSH_ERROR;
            }
    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return SSH_OK;




ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
}


编译器没有显示任何错误,
但是当我运行程序时没有任何结果,
我检查了远程服务器的系统日志,发现以下行:

sshd [12794]:dispatch_protocol_error:键入90 seq 3

请告知可能是什么问题,

谢谢。

最佳答案

似乎您正在尝试不使用主机身份验证功能(例如,从/.ssh/known_hosts检查信息)和用户身份验证(通过公共密钥或密码)进入远程服务器。您应该将这两个功能放在

if (rc != SSH_OK)
{
fprintf(stderr, "Failed %s\n", ssh_get_error(my_ssh_session));
exit(-1);
}


浏览libssh tutorial中的第1章和第2章。

关于c++ - C++使用libssh libary通过SSH检索数据失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18040157/

10-16 20:24