老男孩Day1 作业 (用户名密码验证)

#!/usr/bin/env python

#coding=utf-8
import getpass
import re


'''Day1作业,V1.0,这是一个验证用户名、密码的程序,如果输入密码连续3次错误,则帐号被锁定。
   被锁定的帐号是永久锁定,重启程序无法解锁'''


#假设预先创建了用于用户验证的存贮用户名,密码文件。文件格式为: username,password,x  (其中x为0-3,表示用户状态,
#每输入一次密码错误,x+1,3表未帐号已锁定)


#要求指定用户验证文件的路径
user_db = raw_input('''Please specify the user DB, for example: /tmp/passwd
User DB: ''')


file = open(user_db,'r+')
auth_str = file.readlines()
#获取文件总长
total_size = file.tell()
file.seek(0)
current_size = file.tell()
user_list = []


#获得一个用户列表
while current_size < total_size:
    user_str = file.readline()
    user_list.append(user_str.split(',')[0])
    current_size = file.tell()


#print user_list


while True:
    #预留手动退出机制
    Exit = raw_input('Proceed with authentication? y/n :')
    if not Exit == 'y':
        break
        
    #开始认证操作流程
    username = raw_input('Username: ')
    if not username in user_list: 
        print "invalid username."
        break
    elif username in user_list:
        for i in auth_str: 
            #找出该用户名打头的行
            if re.match(username,i):
                user_line = i
                #找到该用户信息在列表中的索引号
                list_num = auth_str.index(user_line)
                #检查该用户帐号是否已被锁定
                if int(auth_str[list_num][-2]) == 3:
                    print 'Your account has been disabled'
                    break
                elif int(auth_str[list_num][-2]) < 3:
                    password = getpass.getpass('Password: ')
                    #将用户名密码合成可iter的元组,以便逗号连接成字串
                    credential = ','.join((username, password))
                    if credential == auth_str[list_num][0:-3]:
                        #认证成功后,刷新字串中的用户状态信息到零
                        auth_str[list_num] = auth_str[list_num][0:-3] + ',' + str(0) + '\n'
                        print '''Congratulations!
Your username and password are correct!'''   
                        break
                    else:
                        #将用户状态信息转成int,并+1
                        lock = int(auth_str[list_num][-2]) + 1
                        #更新字串中的用户状态信息
                        auth_str[list_num] = auth_str[list_num][0:-3] + ',' + str(lock) + '\n'
                        print 'Your password is wrong.' 
                        print 'You can try %d time(s), typing wrong password constantly will cause your account be disabled.' %(3 - int(lock))


#重新以写方式打开,准备覆盖原文件,否则是追加模式
file = open(user_db,'w+')                       
#覆盖原文件,以更新用户状态信息,其它信息保持不变
file.writelines(auth_str)
#关闭文件,程序终止
file.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值