[英]How to invoke ssh exit from the C program under Linux Platform?
我現有的應用程序具有自定義的CLI-命令行界面。 我正在嘗試使用自定義的CLI從現有應用程序向運行相同應用程序的遠程PC調用ssh。 我無法使用lib ssh創建會話,但是我想使用現有的Linux SSH應用程序。 這是代碼,我曾用過從位於1台PC上的一個應用程序調用ssh到另一台PC的代碼。 我的問題是如何退出SSH。 我看到調用退出沒有任何影響。 我應該怎么做? 這是我執行SSH的示例程序。
INT4 do_ssh(tCliHandle CliHandle, CHR1 *destIp)
{
FILE *writePipe = NULL;
char readbuff[1024];
char cmd[1024];
pid_t pid;
int fd[2];
int childInputFD;
int status;
memset(cmd,'\0',sizeof(cmd));
sprintf(cmd,"/usr/bin/ssh -tt %s",destIp);
/** Enable For debugging **/
//printf("cmd = %s\r\n",cmd);
/** create a pipe this will be shared on fork() **/
pipe(fd);
if((pid = fork()) == -1)
{
perror("fork");
return -1;
}
if( pid == 0 )
{
gchildPid = getpid();
system(cmd);
}
else
{
/** parent process -APP process this is **/
while( read(fd[0], readbuff, sizeof(readbuff)) != 0 )
{
CliPrintf(CliHandle,"%s", readbuff);
printf("%s", readbuff);
}
close(fd[0]);
close(fd[1]);
}
return 0;
}
結果-我看到ssh被調用-我可以輸入密碼,並且可以在遠程PC應用程序上執行SSH。 但是,我不知道如何退出SSH會話。 我應該怎么做才能退出SSH會話?
在子進程中,標准輸出未重定向到您的管道,您需要使用dup2
這樣的:
dup2(fd[1], STDOUT_FILENO);
在調用system
之前。
並且不要使用system
執行程序,而應使用exec
系列功能。
因此子進程應如下所示:
if( pid == 0 )
{
// Make standard output use our pile
dup2(fd[1], STDOUT_FILENO);
// Don't need the pipe descriptors anymore
close(fd[0]);
close(fd[1]);
// Execute the program
execlp("ssh", "ssh", "-tt", destIp, NULL);
}
同樣,在父進程中,完成后需要wait
子進程。
而且,如果您不想打擾管道和進程以及等待之類的事情,只需使用popen
即可,它將為您處理所有操作並為您提供一個不錯的FILE *
。
我想要一個丑陋的方法。 但是,在大型程序中,我們需要維護一個打開了SSH會話的狀態表。 這是將關閉第一個SSH會話的程序。
int exit_ssh()
{
FILE *in;
char buff[512];
char sshCtrlword[512];
printf("ssh Exit Invoked\r\n");
memset(buff,'\0',sizeof(buff));
if(!(in = popen("ps -A x |grep sshd |grep root |grep -v grep", "r")))
if(!(in = popen(gsshCurrentSession,"r")))
{
printf("Error in Popen\r\n");
return -1;
}
while(fgets(buff, sizeof(buff), in)!=NULL)
while(fgets(buff, sizeof(buff), in) != NULL)
{
//printf("%s\r\n", buff);
}
pclose(in);
if( buff[0] != '\0')
{
printf("%s\r\n", buff);
/** we have got something **/
/** prepare control word **/
sprintf(sshCtrlword,"kill -SIGTERM %s",buff);
printf("%s\r\n", sshCtrlword);
if(!(in = popen(sshCtrlword,"r")))
{
printf("Error in Popen() ctrl word..\r\n");
return -1;
}
pclose(in);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.