使用带有 libssh2 lib 的 ssh 发送命令

Sending a command using ssh with libssh2 lib

我尝试使用 libssh2 通过 ssh 发送命令,但无法收到预期的响应。

它与我的 raspberry pi 连接良好。

发送命令的函数:

char * s7c_hardware::sendCmd(char * cmd, bool out)
{
        if (!(channel = libssh2_channel_open_session(session))) return "-1";
        libssh2_channel_setenv(channel, "FOO", "bar");
        if (libssh2_channel_request_pty(channel, "vanilla")) return "-2";
        if (libssh2_channel_shell(channel)) return "-3";
        int rc;
        while ((rc = libssh2_channel_exec(channel, cmd)) ==
            LIBSSH2_ERROR_EAGAIN)
        {
            waitsocket(sock, session);
        }
        char * output = "";
        if (out)
        {
            do
            {
                char buffer[99999];
                rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
                if (rc > 0)
                {
                    fprintf(stderr, "We read:\n");
                    for (int i = 0; i < rc; ++i)
                        fputc(buffer[i], stderr);
                    fprintf(stderr, "\n");
                }
                else {
                    if (rc != LIBSSH2_ERROR_EAGAIN)
                        fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
                }
            } while (rc > 0);
        }
        libssh2_channel_free(channel);
        channel = NULL;
        return output;
}

其中 cmd 是命令,out 是是否需要输出。

如果我尝试发送 "uptime" 并收到正常运行时间,我收到的是:

We read:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Jul  1 10:27:51 2017 from desktop-ca160hm.local

We read:
pi@rasp:~$

我认为请求 shell 和请求执行单个命令是相互排斥的。如果你想 运行 一个命令,得到它的输出,并结束通道(不一定是会话),你应该 运行 libssh2_channel_exec 而不是 运行 libssh2_channel_shell.