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

标签 c linux ssh

我现有的应用程序有一个自定义的 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/

相关文章:

c - 递归和静态变量

bash - 在远程计算机上运行bash脚本的一部分

jenkins - 如何为 Jenkins 设置 ssh key 以通过 ssh 发布

c - 为什么bind函数返回-1(绑定(bind)失败)?

c - 当内存不足时,如何防止变长数组崩溃?

Python 脚本和类位于同一文件中

python - 获取进程文件路径

c++ - shell -内核交互

linux - 通过 ssh 使用 watch

c - 使用宏从一组给定的不同值中查找不等于任何值的值