功能

  • 输入用户名密码:
    • 用户名密码正确 ->返回欢迎信息
    • 用户名密码错误 -> 再次尝试
    • 尝试3次后锁定账户

实现原理

  • 用户名和密码以文件的方式存储
  • 账户锁定后,账户名也以文件的方式存储

示例

### 登录成功
$ python3.7 login.py
Please input your username: test
password:
Dear test, Welcome!!!
###登录失败后可以重试
$ python3.7 login.py
Please input your username: test
password:
Invalid username or password,please try again~
Please input your username: test
password:
Dear test, Welcome!!!
###重试三次都不成功,会锁定账户
$ python3.7 login.py
Please input your username: test
password:
Invalid username or password,please try again~
Please input your username: test
password:
Invalid username or password,please try again~
Please input your username: test
password:
too many attempts, you account has been locked.
###再次登录,会报错
$ python3.7 login.py
Please input your username: test
sorry,your account has been locked.

####代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getpass

datafile = \"datafile.txt\"
errorfile = \"errorfile.txt\"

def check_pass(username, passwd):
    with open(datafile,\'r+\') as f:
        content = f.readlines()
    for i in content:
        if i.split(\',\')[0] == username and i.split(\',\')[1].strip(\'\\n\') == passwd:
            result = 0
            break
    else:
        result = 1
    return result

def write2error(username):
    with open(errorfile, \'a+\') as f:
        f.write(username)
        f.write(\'\\n\')

def check_error(username):
    with open(errorfile, \'r+\') as f:
        cont = f.read()
    if username in cont:
        return False
    else:
        return True

count = 0
while count < 3:
    username = input(\"Please input your username: \")
    is_valid = check_error(username)
    if is_valid:
        passwd = getpass.getpass(\"password:\")
        result = check_pass(username, passwd)
        if not result:
            print(\"Dear %s, Welcome!!!\" %username)
            break
        else:
            count += 1
            if count < 3:
                print(\"Invalid username or password,please try again~\")
            else:
                print(\"too many attempts, you account has been locked.\")
                write2error(username)
    else:
        print(\"sorry,your account has been locked.\")
        break
$ cat datafile.txt
test,1234
test123,5678
$ cat errorfile.txt
test
收藏 打印