linux 伪终端 随笔

初步接触伪终端编程,根据公司一个产品,自己手写了一个示例程序,非常不完善,仅仅是一个随笔,学习下伪终端。
作为一个服务端程序,类似于代理,可记录用户行为。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <pty.h>

void do_trans( int pty);

int main(int argc, char *argv[])
{
    int pty, slave;
    char pty_name[PATH_MAX];
    int ret;
    pid_t child;

    ret = openpty(&pty, &slave, pty_name, NULL, NULL);
    if (ret == -1)
    {
        perror("openpty");
        exit(EXIT_FAILURE);
    }

    child = fork();
    if (child == -1)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if(child == 0)
    {
        close(pty);
        login_tty(slave);
        //execl("/bin/bash", "/bin/bash", NULL);
        execl("/bin/bash", "/bin/bash", "-c", "ssh wcg@192.168.0.162",NULL);
        printf("child bash over !\n");
    }
    close(slave);

    do_trans(pty);
    exit(EXIT_SUCCESS);
}



void do_trans(int pty)
{
    char buffer[800] = {0};
    int ret;

    //write(pty, "w/n", 2);     //象征性的输入不标准的数据,作为查看交互是否成功
    //while(ret = read(pty, buffer, sizeof(buffer)-1))

        printf("\n");

        ret = read(pty, buffer, sizeof(buffer)-1);
        if (ret > 0)
        {
                buffer[ret-1] = 0;   //read是读不到字符串结束符的,需要自己添加,否则printf会出错
                printf(">>%s<<",buffer);//打印出结果
                fflush(stdout);
        }

    do{
        printf("] ");
        fflush(stdout);
        gets(buffer);
        write(pty, buffer, strlen(buffer));
        //printf("recv ret[%d]\n", ret);
        write(pty, "\n", 1);
        ret = read(pty, buffer, sizeof(buffer)-1);
        if (ret <= 0)
        {
            break;
        }
        buffer[ret-1] = 0;   //read是读不到字符串结束符的,需要自己添加,否则printf会出错
        printf(">>%s<<",buffer);//打印出结果
        fflush(stdout);//这步很重要,std中经常有数据滞留在存储区中需要此函数刷新
    }while(ret > 0);

    printf("do_trans over! \n");
    return;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值