2016-08-18 56 views
0

我正在使用libssh在遠程服務器上執行命令。 這裏是我的代碼(返回代碼這裏不檢查簡化,但是所有的人都OK):stderr與libssh在pty模式下

#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; 
} 

輸出是axpected:

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我得到以下錯誤的:

須藤:對不起,你必須有一個tty運行sudo的

回答

2

從概念上講,一個pty代表一個終端(或者更低級別的串行端口) - 每個方向只有一個通道。默認情況下,在pty中運行的進程的標準輸出和標準錯誤都會轉到相同的位置。

(考慮當你在終端運行命令,例如會發生什麼 - 如果你還沒有任何重定向,標準輸出和標準錯誤將出現在屏幕上,而且也沒有辦法告訴他們分開)

一般來說,如果您需要以root身份遠程自動執行運行命令,您應該以root身份進行SSH身份驗證,或者使用NOPASSWD選項授予用戶sudo訪問權限。不要自動輸入密碼。

+0

感謝您的解釋。不幸的是,我不允許ssh作爲根用戶或修改這些服務器上的sudoers配置......我想我必須找到解決方法! – julienc