c - 在 pty 模式下使用 libssh 的 stderr

标签 c libssh

我正在使用 libssh在远程服务器上执行命令。 这是我的代码(为简化起见,此处未检查返回码,但它们都可以):

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

int main() {

    /* opening session and channel */
    ssh_session session = ssh_new();
    ssh_options_set(session, SSH_OPTIONS_HOST, "localhost");
    ssh_options_set(session, SSH_OPTIONS_PORT_STR, "22");
    ssh_options_set(session, SSH_OPTIONS_USER, "julien");
    ssh_connect(session);
    ssh_userauth_autopubkey(session, NULL);
    ssh_channel channel = ssh_channel_new(session);
    ssh_channel_open_session(channel);

    /* command execution */
    ssh_channel_request_exec(channel, "echo 'foo' && whoam");

    char *buffer_stdin = calloc(1024, sizeof(char));
    ssh_channel_read(channel, buffer_stdin, 1024, 0);
    printf("stdout: %s\n", buffer_stdin);
    free(buffer_stdin);

    char *buffer_stderr = calloc(1024, sizeof(char));
    ssh_channel_read(channel, buffer_stderr, 1024, 1);
    printf("stderr: %s", buffer_stderr);
    free(buffer_stderr);

    ssh_channel_free(channel);
    ssh_free(session);
    return EXIT_SUCCESS;
}

输出如预期:

stdout: foo
stderr: command not found: whoam

现在,如果我添加对 ssh_channel_request_pty 的调用在 ssh_channel_open_session 之后:

    ...
    ssh_channel channel = ssh_channel_new(session);
    ssh_channel_open_session(channel);
    ssh_channel_request_pty(channel);
    ssh_channel_request_exec(channel, "echo 'foo' && whoam");
    ...

不再有 stderr 输出:

stdout: foo
stderr:

如果我通过以下方式更改命令:

ssh_channel_request_exec(channel, "whoam");

现在在标准输出上读取错误输出!

stdout: command not found: whoam
stderr:

ssh_channel_request_pty 我遗漏了什么?

有关信息,我正在使用它,因为在某些服务器上,当我使用 sudo 运行命令时出现以下错误:

sudo: sorry, you must have a tty to run sudo

最佳答案

从概念上讲,一个 pty 代表一个终端(或者,在更低的级别上,一个串行端口)——每个方向上只有一个 channel 。默认情况下,在 pty 中运行的进程的标准输出和标准错误都会转到相同的位置。

(例如,考虑一下当您在终端中运行命令时会发生什么——如果您没有重定向任何内容,stdout 和 stderr 都会出现在屏幕上,并且无法区分它们。)

一般来说,如果您需要以 root 身份远程自动运行命令,您应该以 root 身份通过 SSH 登录,或者使用 NOPASSWD 选项授予用户 sudo 访问权限。不要自动输入密码。

关于c - 在 pty 模式下使用 libssh 的 stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39026379/

相关文章:

c - jni-wrapper 在 Windows 上使 JVM 崩溃

c - 从 C 中的套接字文件描述符读取时如何检测分隔符?

c++ - 在 C 程序中调用 C++ 共享库...如何管理?

c - SFTP libssh 失败

c++ - 使用 libssh 进行 SSH 本地端口转发

c - 如何登录到远程 SSH 服务器并使用 libssh 和 [C] 发送命令

c++ - LibSSH C++ 包装器 - 离开范围时的基本远程连接段错误

c - 在验证回调中访问目标域(主机名)

c++ - 如何使用 libssh 运行 makefile?

c++ - 我如何告诉 GCC 为 -l 使用自定义库而不是系统库?