用户登陆验证程序:
主要功能:
1) 用户登陆
2) 登陆失败3次后锁定账户,并记录到文件
3) 登陆成功之后判断用户类型,根据用户类型显示不同菜单
4) 用户类型分为普通用户和管理员权限用户
普通用户权限功能:
a: 搜索用户
b: 修改密码
管理员用户权限功能:
a: 搜索用户
b: 添加用户
c: 删除用户
d: 解锁用户
设计思路:
将用户的个功能通过函数方式进行模块化,登陆后通过用户角色选择不同菜单,
所有数据保存到txt文本文件中,程序启动后将所有数据加载到内存中,每次做修改后重新写到txt文件中去
主要功能:
1) 用户登陆
2) 登陆失败3次后锁定账户,并记录到文件
3) 登陆成功之后判断用户类型,根据用户类型显示不同菜单
4) 用户类型分为普通用户和管理员权限用户
普通用户权限功能:
a: 搜索用户
b: 修改密码
管理员用户权限功能:
a: 搜索用户
b: 添加用户
c: 删除用户
d: 解锁用户
设计思路:
将用户的个功能通过函数方式进行模块化,登陆后通过用户角色选择不同菜单,
所有数据保存到txt文本文件中,程序启动后将所有数据加载到内存中,每次做修改后重新写到txt文件中去
由于测试需要,增加和删除一些用户,为了免于每次都更改txt文件,就增加了删除、添加、解锁等模块
流程图:
源码:
#!/usr/bin/env python # -*- coding: utf-8 -*- import os,json,getpass from datetime import datetime USER_INFO = [] # 存放所有用户信息列表变量 LOGIN_USER = "" # 存放登陆成功的用户名 LOGIN_USER_ROLE = "admin" # 存放登陆用户的权限,初始值为'admin' LOGIN_MAX_ERR_COUNT = 3 # 允许输入错误的最大次数 # 存放用户信息的文件, 当前路径下的 userinfo.txt DB_TXT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'userinfo.txt') def init_data(): """初始化数据,将文件数据加载到全局变量中,返回一个列表""" with open(DB_TXT_FILE,'r') as f: for record in f.readlines(): user_info = json.loads(record.strip()) # 将str类型的数据转成dict USER_INFO.append(user_info) return USER_INFO def get_admin_menus(): """ 显示管理员菜单""" menu_list = ( {'key': '1', 'menu': '[1] search users ', 'function': 'user_search'}, {'key': '2', 'menu': '[2] add new users ', 'function': 'user_add'}, {'key': '3', 'menu': '[3] delete users ', 'function': 'user_del'}, {'key': '4', 'menu': '[4] unlock users ', 'function': 'user_unlock'}, {'key': '5', 'menu': '[5] exit system ', 'function': 'exit_sys'}, ) return menu_list def get_user_menus(): """显示用户菜单""" menu_list = ( {'key': '1', 'menu': '[1] search users ', 'function': 'user_search'}, {'key': '2', 'menu': '[2] modify password ', 'function': 'user_modify_passwd'}, {'key': '5', 'menu': '[5] exit system ', 'function': 'exit_sys'}, ) return menu_list def user_unlock(): """解锁用户""" i = 0 while i < len(USER_INFO): if USER_INFO[i]["name"] == LOGIN_USER: USER_INFO[i]['islocked'] = "1" save_data() break else: i += 1 def user_del(): """删除用户""" print("========== Delete Users ==========") name = "" while len(name) == 0: name = input("input the user name you want to delete:").strip().lower() # 检查用户是否存在 is_exists = check_user_is_exists(name) if is_exists: for i in range(len(USER_INFO)): if USER_INFO[i]['name'] == name: del USER_INFO[i] save_data() print("\033[1;32m\nuser %s delete successfull !\033[0m" % name) break else: print("\033[1;31m\nThe user %s does not exists!\033[0m" % name) def user_add(): """增加用户,添加完1个用户后是否继续添加标志""" add_more_flag = True print('====== Add New Users ===========') while add_more_flag: name = '' password = '' #如果输入用户名为空则不停止输入,直到输入不为空 while len(name) == 0: name = input('username :').strip().lower() while len(password) == 0: password = input('password: ').strip() # 选择用户角色 role = input('user role number [1:admin / 2:user(default)] : ') if len(role) == 0 or role == '2': user_role = 'user' if role == '1': user_role = 'admin' # 组合数据为字典 user_info_dic = {'createtime':datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'password':password, 'name':name, 'userrole':user_role, 'islocked':'0' } USER_INFO.append(user_info_dic) save_data() continue_flag = input('add user successfull, and more?(Y/N)').strip().lower() if continue_flag == 'n' : add_more_flag = False def user_search(): """查找用户""" print("\n======== Search Users =============\n") name = input('Input user name to serach \033[0;32;31m[Enter to show all]\033[0m : ').strip().lower() if len(name) >0: print_search_user_info(name) else: print(" \033[0;32;31m Don't Search....\033[0m") return True def print_search_user_info(name): """打印查找到的信息,并高亮显示""" search_user = name i = 0 record_count = 0 #开始在列表中循环查找 for i in range(len(USER_INFO)): user = USER_INFO[i] # 如果记录的用户包含要查找的名字 if user['name'].count(search_user) > 0: name = user['name'].replace(search_user, '\033[1;31m' + search_user + '\033[0m') role = user['userrole'] cdate = user['createtime'] lockstat = user['islocked'] print('name: %-25s | user role:%-7s | create time: %s | lockstatus: %s \n' % ( name, role, cdate, lockstat)).strip() record_count += 1 print('\n%s records found ' % str(record_count)) def check_user_is_exists(name): """检查用户是否存在(True/False)""" user_exists_status = False for i in range(len(USER_INFO)): user = USER_INFO[i] if user['name'] == name: user_exists_status = True break return user_exists_status def user_modify_passwd(name): """修改密码""" print("========== Modify User's Password ==========\n") i = 0 flag = True while flag: new_password = getpass.getpass('input new password: ') renew_password = getpass.getpass('input new password again :').strip() if new_password ==renew_password: for i in range(USER_INFO): if USER_INFO[i]['name'] == name: USER_INFO[i]['password'] = new_password save_data() flag = False break else: print('new password and confirm password does not match! try again\n') def user_lock(name): """锁定账户""" for i in range(len(USER_INFO)): if USER_INFO[i]['name'] == name: USER_INFO[i]['islocked'] = '1' save_data() break def save_data(): """将数据写入文件""" try: with open(DB_TXT_FILE,'w+') as f: for i in range(len(USER_INFO)): user = json.dumps(USER_INFO[i]) f.write(user + '\n') except Exception as e: print(e.message) def user_unlocked(): """解锁用户""" print("======== Unlock Users ============\n") unlock_user = input("input the user name to be unlock:").strip().lower() for i in range(len(USER_INFO)): if USER_INFO[i]['name'] == unlock_user: USER_INFO[i]['islocked'] = '0' save_data() print('unlocked success') break else: print("no user called %s found!" % unlock_user) def return_function_by_menu(menu_list): """# 根据输入的按键返回函数名称 ,如果选择按键不存在则返回False""" print("========= Choose Menu ========== \n") for menu in menu_list: print(menu['menu']) choose = input('choose what do yo want to do :') # 获取要执行的函数名称 for keys in menu_list: if keys['key'] == choose: return keys['function'] else: print('\n\033[1;31m Error choose\033[0m') return False def user_login(): """ 用户登录""" try_failed_count = 0 # 重试失败次数 print("========= Login system ===========\n") while try_failed_count < LOGIN_MAX_ERR_COUNT: i = 0 uname = input('user name:').strip().lower() upasswd = input('password: ').strip() while i < len(USER_INFO): # 如果找到搜索的用户 if USER_INFO[i]['name'] == uname: LOGIN_USER = uname # 如果正确,检查用户是否锁定,如果锁定 if USER_INFO[i]['islocked'] == "1": print("Sorry,your accout is locked,contact administrator to unlock") exit() else: # 用户存在,检查输入密码是否正确 if USER_INFO[i]['password'] == upasswd: LOGIN_USER_ROLE = USER_INFO[i]['userrole'] print("\033[1;32m\nwelcome %s!\033[0m" % uname) return True # 用户正确,密码验证失败 else: print("login failed,name and password is not avaible,try again!") try_failed_count += 1 break # 没找到? 下一条继续找... else: i += 1 # 搜索一圈都没有找到搜索的用户 else: print("user does not found! try again.") else: # 密码超过3次啦,账户要锁定了 user_lock() print('sorry , you try more then 3 times, i locked this account!') return False if __name__ == "__main__": init_data() if user_login(): # 根据用户角色加载菜单 if LOGIN_USER_ROLE == "admin": menu_list = get_admin_menus() if LOGIN_USER_ROLE == "user": menu_list = get_user_menus() # 根据菜单选择执行函数 while True: func = False while not func: func = return_function_by_menu(menu_list) if func == "user_search": user_search() elif func == "user_add": user_add() elif func == "user_del": user_del() elif func == "user_modify_passwd": user_modify_password() elif func == "user_unlock": user_unlock() elif func == "exit_sys": exit()