2012-03-16 142 views
0

我想從我的C程序通過一些命令,下面是示例程序:如何使用C程序在命令propmt上傳遞命令?

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int main(){ 

    FILE *ssh = popen("ssh [email protected]", "w"); 

    pid_t pid; 
    pid = fork(); 


    if(!ssh) 
    { 
     fprintf(stderr, "Could not open pipe for output.\n"); 
    } 

    if (pid==0){ 

     fprintf(stdout, "Child process properly created.\n"); 
     fputs("user", ssh); 
     fputc('\n', ssh); // enter key 
     _exit(0); 
    } 


    fprintf(stdout, "Exit from child process.\n"); 
    pclose(ssh); 

    return 0 ; 

} 

現在,當我運行這個程序,它要求密碼在命令提示符下是這樣的:

[email protected]'s password: 

我想從我的示例程序中傳遞密碼,而不是從命令提示符處傳遞密碼。 任何人都可以請告訴我如何以編程方式在C中執行此操作。

SSH僅用於例子。也可以用於其他場景。

感謝, Yuvi

+1

如果你的問題是關於'ssh'界面的話,我建議你在superuser.com上提問。 – pmg 2012-03-16 10:08:32

+0

不,它與sssh無關 – Yuvi 2012-03-16 10:13:13

+0

不,這不僅僅與ssh有關,我僅以ssh爲例。有很多情況下,當你使用系統函數啓動任何命令時,它會要求提供一些參數。 – Yuvi 2012-03-16 10:43:57

回答

2

我覺得ssh命令讀取從stdin密碼,在這種情況下,你需要管密碼進入程序,併爲這可以使用popen。 C99/POSIX示例:

#include <stdio.h> 

int main() 
{ 
    FILE *ssh = popen("ssh [email protected]", "w"); 

    fputs("p4ssw0rd", ssh); 
    fputc('\n', ssh); // enter key 

    pclose(ssh); 
} 

未經測試。使用fork/exec/dup等組合可能會有更好的運氣。

+0

我已更新我的代碼,但仍然沒有運氣。 ç你解釋更多如何實現它,我在C編程noob。 – Yuvi 2012-03-16 12:23:09

+0

我也嘗試過所有'fork/exec/dup'的組合,這裏是我遵循http://beej.us/guide/bgipc/output/html/multipage/index.html的refernece鏈接,但仍無法做到這一點。 – Yuvi 2012-03-19 06:34:02

+0

@Yuvi:你不需要分叉。如果你在我的答案中運行上面的代碼而不分叉,會發生什麼? – dreamlax 2012-03-19 08:54:51

0

當它是ssh很多簡化設置ssh密鑰,因此您不必添加密碼。但是,如果你真的想這樣做,使用api命名expect是很容易的。我一直在用自己的成果。

+1

你會請編輯您的答案以添加關於您提到的api的信息? – Freakyuser 2013-03-14 08:16:11