gpt4 book ai didi

c - Linux平台下C程序如何调用ssh退出?

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:32 25 4
gpt4 key购买 nike

我现有的应用程序有一个自定义的 CLI - 命令行界面。我正在尝试使用自定义 CLI 从现有应用程序调用 ssh 到运行相同应用程序的远程 PC。我无法使用 lib ssh 创建 session ,但我想使用现有的 Linux SSH 应用程序。这是代码,我曾经从驻留在一台 PC 中的一个应用程序调用 ssh 到另一台 PC。我的问题是如何退出 SSH。我看到调用 exit 没有任何影响。我该怎么做有什么想法吗?这是我执行 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 session 。我应该怎么做才能退出 SSH session ?

最佳答案

在子进程中,标准输出不会重定向到您的管道,您需要使用例如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 *

关于c - Linux平台下C程序如何调用ssh退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36709343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com