python用户登录,密码错误3次则锁定
需求:
1.输入用户名密码
2.认证成功后显示欢迎信息
3.输错三次后锁定
实现思路:
1.判断用户是否在黑名单,如果在黑名单提示账号锁定。
2.判断用户是否存在,如果不存在提示账号不存在。
3.判断账号密码是否正确,如果正确登录进去。如果不正确有三次输入密码机会。三次全部输错,账号锁定。
方法一:(简易版本)
count = 0
username = "xuyuanyuan"
password = "123"
with open("file.txt",mode="r",encoding="utf8") as f:
file_list=f.readlines()
name=input("请输入用户名:")
#判断输入用户名是否在黑名单中
if name in file_list:#如果用户名在黑名单内
print("您的账户已锁定,请联系管理员!")
else:
#判断用户名是否存在
if name == username:
while count < 3:
pwd = input("请输入您的密码:")
if pwd == password:
print("welcome %s" %name)
break
else:
print("password is error!")
count+=1
else:#如果用户名输入错误超过三次的话,就将用户名加入到黑名单file.txt文件里
print("您输入的次数已经超过三次,账号已锁定,请联系管理员!")
with open("file.txt", mode="a+", encoding="utf8") as f:
test=("%s"%name)
f.writelines(test)
else:
print("该用户名不存在,请重新输入!")
方法二:
# 获取注册用户的信息
with open("db", "r", encoding="UTF-8") as f:
# users = f.readlines() # 读成列表
# users = f.read() # 读到内存
users = {}
for line in f:
user_list = line.strip().split("|") # 分割得到列表
# print(user_list)
users[user_list[0]] = {#往字典里加内容
"username": user_list[0],
"passwd": user_list[1],
"times": user_list[2],
}
# print(users)
# # 读取黑名单
black_list = []
with open("blacklist.txt", "r", encoding="UTF-8") as f2:
for line in f2:
black_list.append(line.strip())
# print(black_list)
#
while True:
# 获取用户输入
username = input("用户名:").strip()
passwd = input("密码:").strip()
# 判断是不是黑名单用户
if username in black_list:
print("用户名已被锁定,请联系管理员!")
# 把用户信息再写回文件
with open("db", "w", encoding="UTF-8") as f4:
for j in users:#遍历的是字典里的key
f4.write(users[j]["username"] + "|" + users[j]["passwd"] + "|" + str(
users[j]["times"]) + "\n")
# 字典是无序的
# f4.write("|".join([lambda x: str(x) for x in users[j].values()])+ "\n")
break
# 判断用户名存不存在
elif username in users:
if passwd == users[username]["passwd"]:
print("登录成功")
# 把之前的错误次数清空
users[username]["times"] = 0
# 把用户信息再写回文件
with open("db", "w", encoding="UTF-8") as f4:
for j in users:
# users[j]是每个用户的字典
f4.write(users[j]["username"] + "|" + users[j]["passwd"] + "|" + str(users[j]["times"]) + "\n")
break
else:
print("用户名密码错误")
# 判断输错次数
users[username]["times"] = int(users[username]["times"]) # 转成int类型
users[username]["times"] += 1
if users[username]["times"] >= 3:
print("用户名被锁定啦!")
# 加入黑名单
black_list.append(username)
with open("blacklist.txt", "w") as f3:
for i in black_list:
f3.write(i+"\n")
# 把用户信息再写回文件
with open("db", "w", encoding="UTF-8") as f4:
for j in users:
# users[j]是每个用户的字典
f4.write(users[j]["username"] + "|" + users[j]["passwd"] + "|" + str(
users[j]["times"]) + "\n")
break
else:
print("用户名不存在")