繁体   English   中英

关于在C语言中使用forkpty创建ssh伪终端的问题

[英]Questions about using forkpty to create pseudo terminal to ssh in C

pid = forkpty (&pty,0,0,0);
if (pid == 0) {
    execl ("/usr/bin/ssh", "ssh", hostname, NULL);
    exit (0);
} else if (pid > 0) {
    ssh_pid = pid;
    ssh_pty = pty;
    if(child_ssh_success()) {
        get_user_input();
        send_user_input_to_child_ssh_and_child_forword_it_to_remote_server();
        get_remote_server_response_from_child();
        display_response_to_stdout();
    }
}

如何判断ssh是否成功?

父母怎样才能知道孩子有成功ssh-ed到远程服务器,所以家长可以送东西到远程服务器?

在父级(即您的else if ( pid>0)条件中)中使用功能waitpid来获取子级的状态

#include   <sys/wait.h>
pid_t waitpid(pid_t pid, int *stat_loc, int options);

引用IBM DeveloperWorks

stat_loc

指向整数的指针,其中wait函数将返回子进程的状态。 如果waitpid函数由于某个进程已退出而返回,则返回值等于该退出进程的pid。 为此,如果stat_loc的值不为NULL,则信息存储在stat_loc指向的位置。 如果状态是从终止的子进程返回的,返回的值为0,则存储在stat_loc所指向的位置的值为0。如果返回值大于0,则可以使用以下宏评估此信息:WEXITSTATUS WIFEXITED WIFSIGNALED WTERMSIG。

因此,如果stat_loc为零,则可以假定SSH正常终止

编辑1

如果您不希望阻止父级,则需要为SIGCHLD设置信号处理程序,并在那里执行同样的waitpid 这次由于孩子已经终止, waitpid将立即返回

这些线上的东西

pid_t pid;
int main ()
{
struct sigaction action;

memset (&action, 0, sizeof(action));
action.sa_handler = sigchld_handler;

if (sigaction(SIGCHLD, &action, 0)) 
    {
    perror ("sigaction");
    return 1;
}

pid = forkpty (&pty,0,0,0);
if (pid == 0) 
{
    execl ("/usr/bin/ssh", "ssh", hostname, NULL);
    exit (0);
} 
else if (pid > 0) 
{
    ssh_pid = pid;
    ssh_pty = pty;
}
}

/* SIGCHLD handler. */
static void sigchld_handler (int sig)
{
    int chld_state;

    while (waitpid(pid,&child_state,options) > 0) 
    {
       if (WIFEXITED(chld_state)) 
       {
           printf("Child exited with RC=%d\n",WEXITSTATUS(chld_state));
       }
    }

}

pid global,以便您也可以从sigchld_handler访问它。 通常ssh对于SUCCESS返回0 ,对于失败返回255 (或其他一些正值),尽管我对此不确定。

编辑2

从我们的讨论中,我看到您也希望在远程服务器上执行命令。 我建议你这样运行ssh

ssh root@remoteserver.com 'ls -l'

您可以通过execl()传递ssh这些参数,如EDIT1所述 ,您可以检查其返回值以验证一切是否正常。 另外,由于您正在通过代码执行ssh ,因此您可能不想手动输入密码。 这是减少密码的方式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM