用户认证练习
用户输入用户名密码,密码认证三次,都输入不正确锁定
账户密码记录文件 data,
hong|123 ding|123
锁定账户密码文件 data1,
hong
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import os,sys,getpass 2 from pathlib import Path 3 f = open(Path(__file__).parent / "data","r") #指定账户文件 4 d = open(Path(__file__).parent / "data1","r+") #读取黑名单 5 6 #看是否锁定 7 name_in = input("Pleae input your name:").strip() 8 for black in d: 9 if name_in == black.strip(): 10 print("\033[31m Your count has locked \033[0m") 11 sys.exit() 12 # sys.exit("Your count has locked,Please contect the manager!") 13 #判断是否为有效账户 14 if name_in not in f.read(): 15 sys.exit("Please check your name,invalid name") 16 f.close() 17 18 19 for i in range(3): 20 f = open(Path(__file__).parent / "data","r") 21 pass_in = getpass.getpass("Please input your password:") #用户输入密码 22 ##开始验证用户密码 23 for line in f: #读取账户 24 f_name = line.split("|")[0] #获取用户名 25 f_pass = line.split("|")[1].strip() #获取密码 26 if name_in == f_name and pass_in == f_pass: 27 sys.exit("Wellcome") 28 else: 29 cout_t = 2 - i 30 print("password error,please try again,you have %s times" % cout_t) 31 break 32 f.close() 33 else: 34 d.write(name_in + "\n") #失败3次加入黑名单 35 sys.exit("your count has locked") 36 d.close()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import os,sys,getpass #导入模块 2 from pathlib import Path 3 os.system('clear') 4 #u_f = open(Path(__file__).parent / "data","r") #打开文件 5 d_f = open(Path(__file__).parent / "data1","r+") 6 7 for i in range(3): 8 name_in = input("Please input your name:") #用户输入用户名 9 with open(Path(__file__).parent / "data","r") as u_f: #读取用户名 10 for u_list in u_f: 11 u_name = u_list.split("|")[0].strip() #获取用户名 12 u_pass = u_list.split("|")[1].strip() #获取用户密码 13 if name_in == u_name: #如果有效 14 for d_u in d_f: #验证是否在黑名单 15 if name_in == d_u.strip(): 16 print("\33[31m Your count has been locked! \33[0m") 17 sys.exit() 18 else: 19 for j in range(3): 20 pass_in = getpass.getpass("Please input your password:") #输入用户名 21 if pass_in == u_pass: 22 print("\33[32m Wellcome to system ! \33[0m") 23 sys.exit() 24 else: 25 cout_t = 2 - j 26 print("password error,please try again,you have %s times" % cout_t) 27 continue 28 else: 29 d_f.write(name_in + "\n") #失败3次加入黑名单 30 sys.exit("your count has locked") 31 d_f.close() 32 else: 33 print("Please input valid acount!") #无效用户名重试 34 pass 35 else: 36 sys.exit("Sorry, the name is invalid") #无效用户名,退出