码迷,mamicode.com
首页 > 系统相关 > 详细

Linux终端下简单的登录程序 密码不回显

时间:2014-06-19 06:06:03      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   color   com   

在Linux进行登录是输入密码不会被回显,所以我也写了个简单的登入程序,使得在输入密码时不再进行回显。

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>

#define   USER_NAME            "username"
#define   USER_PASS            "userpass"

#define   MAX                  20

#define   ECHOFLAGS           (ECHO | ECHOE | ECHOK)

int  set_disp_mode(int fd, int option) {
    int  err;
    struct termios  term;

    if (tcgetattr(fd, &term) == -1) {
        fprintf(stderr, "Can\‘t get the attribution of the terminal!\n");
        exit(1);
    }

    if (option) {
        term.c_lflag |= ECHOFLAGS;
    }
    else {
        term.c_lflag &= ~ECHOFLAGS;
    }

    err = tcsetattr(fd, TCSAFLUSH, &term);

    if (err == -1 && err == EINTR) {
        fprintf(stderr, "Can\‘t set the attribution of the terminal!\n");
        exit(1);
    }

    return  0;
}

int  get_passwd(char* passwd, int size) {
    int  c;
    int  n = 0;

    fprintf(stderr, "Please input password:");

    do {
        c = getchar();
        if (c != \n && c != \r) {
            passwd[n++] = c;
        }
    } while (c != \n && c != \r && n < (size-1));

    passwd[n] = \0;

    return n;
}

bool check_login(const char* name, const char* passwd) {
    int nlen = strlen(USER_NAME);
    int plen = strlen(USER_PASS);
    return  (strncmp(name, USER_NAME, nlen) == 0) &&
            (strncmp(passwd, USER_PASS, plen) == 0);
}

int  main(void) {
    char  name[MAX];
    char  passwd[MAX];
    
    LOGIN:
    fprintf(stderr, "login user:");
    fgets(name, MAX, stdin);
    name[strlen(name)-1] = \0;

    set_disp_mode(STDIN_FILENO, 0);

    get_passwd(passwd, MAX);

    if (check_login(name, passwd)) {
        fprintf(stderr, "\nHello %s, Welcome!\n", name);
    }
    else {
         fprintf(stderr, "\n");
         set_disp_mode(STDIN_FILENO, 1);
         goto LOGIN;
    }

    set_disp_mode(STDIN_FILENO, 1);

    return  0;
}

 

Linux终端下简单的登录程序 密码不回显,布布扣,bubuko.com

Linux终端下简单的登录程序 密码不回显

标签:style   class   blog   code   color   com   

原文地址:http://www.cnblogs.com/coder-zhang/p/3789588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!