Python練習,模擬用戶登錄接口
阿新 • • 發佈:2017-12-02
python 登錄 運維 模擬登錄 練習 實現需求如下:
同一個用戶名連續失敗三次則鎖定,不管用戶名是否在,鎖定後在下次運行腳本登錄是同樣是鎖定狀態
使用文件存儲用戶名和密碼信息,與文件裏面的用戶名密碼進行認證對比
用戶名不存在和密碼錯誤提示不可以相同,登錄成功,賬號被禁用,密碼錯誤,用戶不存在需要有相關的提示信息
腳本如下:
#!/usr/bin/python #coding:utf8 class Login(): def userInfo(self): #將用戶名密碼信息文件處理成一個字典 with open("userinfo.txt", "r") as file: userDict = {} for i in file: userList = i.split(":") userDict.update({userList[0]:userList[1].rstrip()}) return userDict def lock_userInfo(self): #將否定的用戶的文件處理成一個列表 with open("lock_userinfo.txt", "r") as file: userList = [] for i in file: userList.append(i.rstrip()) return userList def lockUser(self, username): #如果相同用戶登錄錯誤三次就調用此函數,將用戶永久瑣定,寫入文件 with open("lock_userinfo.txt", "a") as file: file.write(username + "\n") def userLogin(self): #登錄 lockList = [] while True: username = raw_input("請輸入用戶名: ") password = raw_input("請輸入用戶密碼: ") if lockList.count(username) < 3: lock = self.lock_userInfo() user = self.userInfo() if username not in lock: if username in user: if user[username] == password: print("登錄成功") else: lockList.append(username) print("密碼錯誤") else: lockList.append(username) print("用名不存在") else: print("此用戶已禁用") else: self.lockUser(username) print("用戶登錄次數超過限制,已禁用") if __name__ == "__main__": login = Login() login.userLogin()
腳本使用方法:
首先需要在腳本所在的目錄下面創建兩個文件lock_userinfo.txt和userinfo.txt
userinfo.txt存入用戶信息,一行一個用戶,用戶名和密碼用冒號分開,不要有空格,如下所示:
lock_userinfo.txt為被否定的用戶列表文件,初始為空,如果有同一用戶登錄出錯三次就會被永久寫入該文件,無法登錄,解鎖用戶就是刪除該文件裏面的用戶名
運行結果如下:
正確登錄
密碼輸入錯誤三次
用戶被永久否定後再登錄
用戶名輸入錯誤多次後
這裏是第五次才禁用,和需求有點出入,邏輯還存在一些問題,沒有想到好的方法
Python練習,模擬用戶登錄接口