天天看點

簡單的Python登陸認證小程式

  使用Python編寫登陸認證小程式、使用者連續 3 次輸入密碼錯誤即鎖定使用者。

############# start ###############

#!/usr/bin/env python

import os

import sys

#

os.system('clear')  

userfile = file('user_id.txt', 'r+')

userlist = []

userdict = {}

if os.path.isfile("user_id.txt"):

    pass

else:

    print '沒有定義使用者的檔案!'

    sys.exit

#userfile.readlines()

for userline in userfile:

    useritem = userline.strip()

    #生成系統的使用者清單

    value_useritem = useritem.split(';')

    #基本判斷添加取出

    value_username = value_useritem[0].strip()

    value_passwd = value_useritem[1].strip()

    lock_value = int(value_useritem[-1])

    logincount_value = int(value_useritem[-2])

    #生成使用者名清單

    userdict[value_username] = {'name':value_username, 'pwd':value_passwd, 'lockcount':logincount_value, 'locknum':lock_value}

flag = 'Ture'

counter = 0

while flag :

    username = raw_input('請輸入使用者名:')

    userpasswd = raw_input('請輸入密碼:')

    #判斷是否是系統使用者

    if username not in userdict.keys():

        print '這個使用者不存在!' 

        break

    elif userdict[username]['locknum'] == 0 and userdict[username]['lockcount'] < 3 :

        if userpasswd == userdict[username]['pwd'].strip(): 

            print '歡迎登陸系統!!!'

            break

        else:

            counter += 1

            userdict[username]['lockcount'] += 1

            userfile = file('user_id.txt', 'w+')

            for t in userdict.values():

                wuserlist = [str(t['name']), str(t['pwd']), str(t['lockcount']), str(t['locknum'])]

            #wuserlist = t.values()

                wuserlist_str = ';'.join(wuserlist)

            #userfile.seek(0)

                userfile.write(wuserlist_str + '\n')

            if counter >2 :

                print '密碼輸入錯誤達到3次,退出登陸。'

                break;

    else:

        print '該使用者賬号已被鎖定!'

        sys.exit('請聯系管理者解鎖!')

    continue;

userfile.close()

############# end ###############

其中,user_id.txt的格式為:

使用者名;密碼;錯誤密碼次數;管理者手動鎖定賬戶,如下:

[root@docker day1]# cat user_id.txt 

hejp;123;0;0

test;456;0;0

使用者hejp輸入三次密碼錯誤後,會在user_id.txt裡顯示錯誤密碼次數為3,此時該使用者鎖定,隻要把它改為0後就能解鎖。

hejp;123;3;0