[置顶] 验证用户登录(perl)

#!/usr/bin/perl
use strict;
use warnings;
use Term::ReadPassword;  #隐藏密码

=pod 验证用户登录 passwd file ./switch 是存放用户名密码的数据文件 数据文件的格式:用户名 密码 =cut

my (%names,@logusers,$time); #//%names来用验证用户名和密码 @logusers用来保持用户的登录信息
chomp($time=qx(date));
open(LG,'>>','./login.log'); #用于记录用户的登录操作信息

sub user_info {
   open(FL,'<','./switch') or die "Cant open './switch':$!\n";
   while(<FL>) #读取密码文件的数据信息
   {
      my($user,$pass)=split /\s+/;
      $names{$user} = $pass;  #存储账户和密码
   }
}
#print "Please input your name: ";
LINE: while(1)
{
   &user_info(); #动态刷新用户信息(当有新注册用户的写入数据文件时)
   print "Please input your name: ";
   chomp(my $user=<STDIN>);
   my $count=0;
   if (exists $names{$user}) #判断用户是否存在,如果存在则认证密码,否则重新验证用户
   {
      while(1)
      {
         ++$count;
         if($count >= 4) #判断密码输入的次数,尝试3次密码错误,重新输入用户名
         {
           print "Password to try the 3 error, please re-enter the user name\n";
           redo LINE; #返回最外层循环
         }
         chomp(my $pass=read_password('password: '));
         if("$pass" eq "$names{$user}") #验证密码的正确性,验证成功后将账户密码存储数组,否则重新输入密码
         {
             print "Login Success!\n";
             push @logusers,"$user";push @logusers,"$pass";
             print LG "$time => The $user login successful\n";
             last LINE;
         }
         else
         {
             print "passwd wrong,try again\n";
             print LG "$time => The $user input passwd is wrong\n";
             redo; #无条件的返回上次循环
         }
       }
   }
   else
   {
      print LG "$time => The $user is not exists at the system\n";
      print "Your name is not exists or wrong,try again\n";
      redo ; #无条件的返回上次循环
   }
}
close(FL);
close(LG);
print "Hello test\n";

你可能感兴趣的:(perl,验证用户登录)