1. 程式人生 > >python登陸認證程序

python登陸認證程序

brush 賬號 字典 ngs 啟動程序 str passwd bre 定義


1. 讓用戶輸入用戶名密碼 2. 認證成功後顯示歡迎信息、程序結束 3. 輸錯三次後退出程序 升級需求: 1. 可以支持多個用戶登錄 (提示:用戶可以通過列表或者是字典進行存儲) 2. 用戶3次認證失敗後,退出程序,再次啟動程序嘗試登錄時,還是鎖定狀態(提示:需把用戶鎖定的狀態存到文件裏)

代碼一(只用到了列表),需要在同級別目錄先創建名為lockedname.txt的空文件。
#!/usr/bin/env python
# coding=utf-8
# __author__ = "zhaohongwei"
# Date: 2019/1/27


name_list = ["zhangsan","lisi","wangwu"]  # 用戶名列表
passwd_list = ["zhangsan666","lisi666","wangwu666"]  # 用戶的密碼列表
count = [0, 0, 0]  # 用戶登錄密碼錯誤的次數計數
while True:
    name_index = 999999  # 定義一個不存在的用戶的下標
    name = input("請輸入你的姓名:").strip()
    passwd = input("請輸入你的密碼:").strip()
    with open("lockedname.txt","r+") as f:
        locked_name = "".join(f.readlines()).splitlines()
        if name in locked_name:
            print("用戶已經被鎖定,請聯系管理員")
            continue
    for i in range(len(name_list)):
        if name == name_list[i]:
            name_index = name_list.index(name_list[i])
    if name_index == 999999:
        print("用戶名不存在,請重新輸入")
        continue
    if name == name_list[name_index] and passwd == passwd_list[name_index]:  # 判斷用戶名密碼
        print("歡迎 %s 同學"%(name_list[name_index]))
        break
    else:
        count[name_index] += 1  # 同一個用戶名輸錯密碼加一
        print("密碼錯誤")
        if count[name_index] == 3 :
            print("3次密碼錯誤,用戶賬號已被鎖定")
            with open("lockedname.txt","a+") as f:
                f.writelines(name_list[name_index]+"\n")
            break

代碼二(修改版,用到了字典)

#!/usr/bin/env python
# coding=utf-8
# __author__ = "zhaohongwei"
# Date: 2019/1/27

import json

user = {
    "zhangsan": ["zhangsan666",3,False],
    "lisi": ["lisi666",0,True],
    "wangwu": ["wangwu666",0,True]
}    #用戶名:[密碼,密碼輸錯次數,False鎖定用戶]
while True:
    name = input("請輸入你的姓名:").strip()
    try:
        with open("lockedname.txt","r+",encoding="utf-8") as f:
            user = json.load(f)  #若是有lockedname.txt文件,則user重新賦值
    except Exception as err:
        pass
    if name not in user:
        print("用戶名不存在,請重新輸入")
        continue
    elif user[name][2] == False:
        print("用戶已經被鎖定,請聯系管理員")
        continue
    elif name in user:
        passwd = input("請輸入你的密碼:").strip()
        if passwd == user[name][0]:  # 判斷用戶名密碼
            print("歡迎 %s 同學"%(name))
            user[name][1] = 0
            with open("lockedname.txt", "w", encoding="utf-8") as f:
                json.dump(user, f)
            break
        else:
            user[name][1] += 1  # 同一個用戶名輸錯密碼加一
            print("密碼錯誤")
            if user[name][1] >= 3:
                print("用戶賬號已被鎖定")
                user[name][2] = False
            with open("lockedname.txt", "w", encoding="utf-8") as f:
                json.dump(user, f)

python登陸認證程序