我正在使用 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/