標籤:成功 view mat 登陸 gpo opened for line 存在
作業:編寫登陸介面
- 輸入使用者名稱密碼
- 認證成功後顯示歡迎資訊
- 輸錯三次後鎖定
帳號檔案account.txt內容如下:
sam 123
david 12
kevin 123
lin 12
tailen 123
jack 12
鎖檔案account_lock.txt預設為空白
1、流程圖如下:
二、針對帳號檔案裡的不存在的使用者也可以進行判斷並鎖定,針對使用者和密碼共有三次錯誤重試機會
1 #_*_ coding:utf-8 _*_ 2 3 import sys,os,getpass 4 5 os.system(‘clear‘) 6 7 retry_limit = 3 8 retry_count = 0 9 10 account_file = ‘account.txt‘11 lock_file = ‘account_lock.txt‘12 13 while retry_count < retry_limit: #只要重試不超過3次就不斷迴圈14 username = raw_input(‘\033[31;43mUsername:\033[0m‘)15 username = username.strip()16 lock_check = open(lock_file) #當使用者輸入使用者名稱後,開啟LOCK 檔案 以檢查是否此使用者已經LOCK了17 18 for line in lock_check.readlines(): #迴圈LOCK檔案 19 if username == line.strip(‘\n‘): #去掉分行符號20 sys.exit(‘\033[35mUser %s is locked!!!\033[0m‘ % username) #如果LOCK了就直接退出21 password = raw_input(‘\033[32;41mPassword:\033[0m‘) #輸入密碼22 23 f = open(account_file,‘r‘) #開啟帳號檔案 24 match_flag = False # 預設為Flase,如果使用者match 上了,就設定為 True 25 26 for line in f.readlines(): 27 user,passwd = line.strip(‘\n‘).split() #去掉每行多餘的\n並把這一行按空格分成兩列,分別賦值為user,passwd兩個變數28 if username == user and password == passwd: #判斷使用者名稱和密碼是否都相等29 print(‘hello, %s !!‘ % username)30 match_flag = True #相等就把迴圈外的match_flag變數改為了True31 break #然後就不用繼續迴圈了,直接 跳出,因為已經match上了32 f.close()33 34 if match_flag == False: #如果match_flag還為False,代表上面的迴圈中跟本就沒有match上使用者名稱和密碼,所以需要繼續迴圈35 print(‘sorry,%s is unmatched‘ % username)36 retry_count += 1 #計數器加137 else:38 print(‘wlecome login my learning system!‘)39 break #使用者成功登入,退出指令碼40 41 else:42 print("you account %s is locked!!!" % username)43 g = open(lock_file,‘a‘)44 g.write(username) #被鎖使用者追加到使用者鎖檔案45 g.write(‘\n‘) 46 g.close()View Code
python之編寫登陸介面(第一天)