首页 > 代码库 > 脚本小练——用户认证

脚本小练——用户认证

需求:输入用户名和密码,认证成功后显示欢迎信息,输错三次后锁定


shell:

#!/bin/bash
# Auth user login

user="hlf"
pass="123456"
lock_file=login.lock
[ -f ${lock_file} ] || touch ${lock_file}

for i in `seq 3`
do
        read -p "username:" username
        read -p "password:" password

        if [ -z "$username" -o -z "$password" ];then
                echo "用户名和密码不能为空,请重新登陆:"
                LoginSuccess=‘false‘
        elif grep -q "\b$username\b" ${lock_file};then
                echo "账户被锁定,请联系管理员!"
                LoginSuccess=‘lock‘
        else
                if [ "$username" = $user -a "$password" = $pass ];then
                        echo "welcome to my system"
                        LoginSuccess=‘true‘
                else
                        echo "用户名或密码错误,请重新登陆:"
                        LoginSuccess=‘false‘
                fi
        fi
        [ $LoginSuccess = true -o $LoginSuccess = lock ] && break

done
if [ $LoginSuccess = false ];then
        echo "登陆三次失败,账户被锁定!!!" 
        [ -z "$username" ] || echo "$username" >> ${lock_file}
fi


python:

user.txt格式:

用户名 密码

#encoding: utf-8
#!/usr/bin/python
# Auth user login

user_file = "user.txt"
lock_file = "login.lock"

#生成字典,保存用户名密码
user_dict = {}
f = file(user_file)
for line in f.readlines():
        user_dict[line.split()[0]] = line.split()[1]
f.close()

#定义元组,保存被锁定的账户
lock_tup = ()
f = file(lock_file)
for line in f.readlines():
        line = line.strip(‘\n‘)
        tup = (line,)
        lock_tup = lock_tup + tup
f.close()

#用户认证
for i in range(3):
        username = raw_input("username:").strip()
        password = raw_input("password:").strip()

        if len(username) == 0 or len(password) == 0:
                print "用户名和密码不能为空,请重新登陆:"
                LoginSuccess=‘false‘
        elif username in lock_tup:
                print "账户被锁定,请联系管理员!"
                LoginSuccess=‘lock‘
        else:
                if  password == user_dict[username]:
                        print "welcome to my system"
                        LoginSuccess=‘true‘
                else:
                        print "用户名或密码错误,请重新登陆:"
                        LoginSuccess=‘false‘
        if LoginSuccess == "true" or LoginSuccess == "lock":break

#循环三次后
if LoginSuccess == "false" and username != "":
        print "登陆三次失败,账户被锁定!!!"
        f = file(lock_file,‘a‘)
        f.write(username + ‘\n‘)
        f.close


脚本小练——用户认证