本程序主要是实现对python装饰器的进一步利用, 执行的过程如下:
- 用户输入用户名密码
open()
读取用户文件,判断用户名密码,判断是否锁定- 如果用户登入错误次数等于2则代表已经被锁定,则执行下一次输入
- 如果用户没有被锁定,但用户名密码错误,则提示用户名密码错误,并在文件内把登入错误计数加1,进入下一次输入
- 如果经过上面的判断,则直接进入
login_index
函数(shell函数)
用户列表文件
1 2 3 4 5 | ['charl', '123', 0] ["sb1","1233",1] ['sb2', '1231', 2] ['sb3','1232',0] |
程序实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | #!/bin/python3 # -*- coding:utf-8 -*- ''' python login auth example ''' #imports import getpass,os #functions def lock_user(username): ''' username -> modify userlist file ''' temp_str = "" with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read: for line in file_read: temp_list = eval(line) if temp_list[0] == username: temp_list[2] += 1 temp_str += str(temp_list)+"\n" continue temp_str += line file_write.write(temp_str) os.rename("userlist.swp", "userlist") def user_input(): ''' input username&&password -> return username&&password ''' username = input("username:") password = getpass.getpass("password:") return username,password def check_user(username,password = '',type = 'check'): ''' username,password,check -> return t||f #username password lock check username,password,lock -> return t||f #username locked or not ''' flag = False with open("userlist",'r') as file_read: for line in file_read: temp_list = eval(line) if type == 'check': if username == temp_list[0] and password == temp_list[1] \ and temp_list[2] < 2: return True #user not locked and correct user and pass if type == 'lock': if username == temp_list[0] and temp_list[2] >= 2: return True #user has been locked else: return False #login decorator def auth(func): def wrapper(*args,**kwargs): while True: username,password = user_input() #get input if check_user(username, password,type='check'): #juge username and password correct or not print("login success!") func(username) #shell function else: if check_user(username, password, type='lock'): #juge user locked or not print("This account has been locked!") else: lock_user(username) #lock count += 1 print("incorrect username or password!") return wrapper #shell function @auth def login_index(username = ""): while True: command = input("%s>" %username) #ask input command if command == 'ls': print( ''' bin dev home lib64 media opt root sbin sys usr boot etc lib lost+found mnt proc run srv tmp var ''') if command == 'exit': #exit shell print("byebye!") exit() #main program def main(): login_index() #program entry if __name__ == '__main__': main() |