python3.x Day1 用户登录程序练习

训练1:

模拟登陆:

1. 用户输入帐号密码进行登陆

2. 用户信息保存在文件内

3. 用户密码输入错误三次后锁定用户

login2.py:

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 # author : Wang Yue
  4 
  5 import sys,hashlib,getpass,time
  6 
  7 #定义用户类
  8 class real_user(object):
  9     real_name=''#用户名
 10     real_pwd=''#密码
 11     login_count=0 #登录次数
 12     lock_time=0 #锁定时间
 13     #重写构造函数,用于初始化用户类实例
 14     def __init__(self,real_name,real_pwd):
 15         self.real_name=real_name
 16         self.real_pwd=real_pwd
 17     #属性设定方法
 18     def set_lock(self,lt):
 19         self.lock_time=lt
 20 
 21     def get_login_count(self):
 22         return self.login_count
 23 
 24     #定义业务方法,用于锁定自身用户实例的方法
 25     def lock_me(self,seconds):
 26         self.lock_time=seconds
 27         lock_info=self.real_name + "," + str(self.lock_time) + "\n"
 28         return lock_info
 29     #定义业务方法,用于解锁自身用户实例
 30     def unlock_me(self,u_name):#lock_time float
 31         if u_name == self.real_name and time.time() >= self.lock_time:
 32             self.lock_time = 0
 33             return True
 34         else:
 35             return False
 36 
 37 #单独封装的函数,主函数中会使用到的方法,公共性的,对于主函数透明
 38 #从文件(数据源)中,将已经存在的用户信息,写为字符串数组,返回该数组
 39 def get_file_line(file,mode_file):
 40     userlist = []
 41     with open(file,mode=mode_file,encoding='utf-8') as filedb:
 42         filedb.flush()
 43         filedb.seek(0)
 44         fileline=filedb.readline()
 45         while fileline:
 46            userlist.append(fileline)
 47            fileline=filedb.readline()
 48     return userlist
 49 
 50 #将信息回写到文件,主函数中用于写黑名单
 51 def input_line_file(file,info):#info is a list
 52     with open(file,mode="a+",encoding="utf-8") as filedb:
 53         for info_line in info:
 54             filedb.write(info_line + "\n")
 55 
 56 #将信息从文件中删除,含有信息的行会被删除
 57 def delete_line_file(file,info):
 58     with open(file,mode="w+",encoding="utf-8") as filedb:
 59         filedb.flush()
 60         filedb.seek(0)
 61         for line_one in filedb.readlines():
 62             if info in line_one:
 63                 line_info=line_one.split()
 64                 if line_info[0] == info:
 65                     continue
 66             filedb.write(line_one)
 67 
 68 #校验登录,参数:登录的用户名,密码,真是存在的用户实例list
 69 #用户名密码,检查锁定状态
 70 #返回值:登录成功,当前锁定。(用户名压根不存在的话,在主函数就过滤掉了)
 71 def verify_me(u_name,u_pwd,user):
 72     if user.lock_time != 0:
 73         return "fuck you,fuck off"
 74     if time.time()>=user.lock_time:
 75         user.lock_time=0
 76     if user.real_name == u_name:
 77         user.login_count +=1
 78     if user.real_name == u_name and user.real_pwd == u_pwd:
 79         user.login_count = 0
 80         user.lock_time = 0
 81         return "sucess"
 82     else:
 83         return "retry once....."
 84 
 85 #获得MD5,密码在文件中存放时是MD5加密的
 86 def get_md5_enc(need_md5_char):
 87     utf_kkk = need_md5_char.encode(encoding="utf-8")
 88     m = hashlib.md5()
 89     m.update(utf_kkk)
 90     md5_char = m.hexdigest()
 91     return md5_char
 92 
 93 #主函数
 94 if __name__ == '__main__':
 95     userlist=get_file_line("user_db.doo","r") #获取用户信息,存成信息list
 96     locklist=get_file_line("lock_db.doo","r") #获取黑名单信息,存成信息list
 97     user=[]  #定义用户实例数组
 98 
 99     #初始化全部用户实例,使用用户类的构造函数
100     for user_line in userlist:
101         name_pwd=user_line.split("::++++::")
102         name=name_pwd[0].strip()
103         pwd=name_pwd[1].strip()
104         user.append(real_user(name,pwd))
105 
106     #遍历用户实例数组,将锁定属性赋值
107     for lock_inf in locklist:
108         lock_info=lock_inf.strip()
109         if lock_info =='':
110             continue
111         lockif=lock_info.split(',')
112         for user_ok in user:
113             if user_ok.real_name==lockif[0]:
114                 user_ok.set_lock(float(lockif[1].strip()))
115 
116     #以下开始正式业务
117     count = 0 #用于记录登录次数
118     while True:
119         #输入用户名密码,并将密码MD5
120         print("hello let try login")
121         username=input("username:")
122         passinput=input("password:")
123         passwd = get_md5_enc(passinput)
124 
125         #从用户类实例list中,确定用户行为:用户名是否正确?密码是否正确?
126         for user_one in user:
127             #用户名不正确,3次,提示需要注册,程序结束
128             if user_one.real_name !=username:
129                 if count >2:
130                     print("you need reg.....")
131                     sys.exit(0)
132                 continue
133 
134             #用户名正确,密码情况:
135             check_login=verify_me(username,passwd,user_one)
136             #密码正确,登录成功
137             if check_login =="sucess":
138                 print("hello:{_name},login success!!!!".format(_name=username))
139                 delete_line_file("lock_db.doo",username)
140                 sys.exit(0)
141             #密码不正确,该用户实例的登录次数+1,避免仅提供三次输入用户名密码就结束的情况,不然中途换了用户名,就出bug了
142             #用户名正确时,用户登录次数超过3次,将被锁定5分钟。
143             elif user_one.get_login_count() > 2 and user_one.real_name == username:
144                 lock_time=time.time()+300
145                 lock_info=user_one.lock_me(lock_time)
146                 lockjj=[]
147                 lockjj.append(lock_info)
148                 input_line_file("lock_db.doo",lockjj)
149                 print("fuck you,lock you 5m!!!!")
150                 sys.exit(0)
151             #登录状态为锁定的话,就结束程序
152             elif check_login =="fuck you,fuck off":
153                 print("fuck you,fuck off:{_name}.you were locked".format(_name=username))
154                 sys.exit(0)
155             #解锁用户:锁定时间算法为(锁定发生时,增加300秒),当前时间>=锁定的时间,即可解锁
156             elif user_one.lock_time <= time.time() and user_one.real_name==username:
157                 user_one.unlock_me(username)
158                 delete_line_file("lock_db.doo",username)
159                 continue
160             #判定用户名不正确的使用登录次数,超过3次就结束
161             elif count <2:
162                 count +=1
163                 break
164         count +=1

因为密码是MD5加密的,所以无法直接维护数据源文件,所以提供注册程序:\

reg.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author : Wang Yue

import hashlib,getpass,sys

#MD5加密算法
def get_md5_enc(need_md5_char):
    utf_kkk = need_md5_char.encode(encoding="utf-8")
    m = hashlib.md5()
    m.update(utf_kkk)
    md5_char = m.hexdigest()
    return md5_char


print("input username,and passwd")
#以两种方式打开文件的流,增加模式,只读模式
user_db=open("user_db.doo",mode="a+",encoding="utf-8")
check_db=open("user_db.doo",mode="r",encoding="utf-8")

#主业务程序:
while True:
    #获取输入的用户名,密码
    username = input("username:")
    passwd = getpass.getpass("password:")
    passwd2 = getpass.getpass("password confirmation:")
    #判断确认密码是否一致。
    if passwd == passwd2:
        cc_status=0
        check_line=check_db.readline()
        while check_line: #在密码文件中,检查是否已经存在了需要添加的用户名
            cl=check_line.split("::++++::")
            if cl[0] == username:
                print("repetition username !!! add user faild,username:{_username}".format(_username=username))
                cc_status=1
            check_line=check_db.readline()
        if cc_status == 1: #确定是否要退出程序
            quit_con = input("quit me (y/n):::")
            if quit_con == "y":
                user_db.close()
                check_db.close()
                sys.exit()
            else:
                continue
        #如果能走到这一步,说明,就是要添加一个用户了
        en_pass = get_md5_enc(passwd) #MD5密码。
        var_char = username + "::++++::" + en_pass + "\n" #设定好约定的用户名密码之间的分隔,及回行符
        user_db.write(var_char) #写入用户数据文件
        print("succed username:{_username}".format(_username=username))
    else:
        print("The input is inconsistent(password)")
    quit_con = input("quit me (y/n):::")
    if quit_con == "y":
        user_db.close()
        check_db.close()
        sys.exit(0)

以下提供数据源文件样例:

user_db.doo:

wangyue::++++::1aa7657007cd60caf3e90a3d4abc8e1b
renchunlin::++++::af2e8cbcc3b08e63a6782b65565848e7
laopeng::++++::9ef3a32fdefa9fe7e9e2edfeaa65fd6f
guohui::++++::cfb599bba2e35793a620de1ecec0d09a


 

posted @ 2017-10-21 15:25  王玥  阅读(294)  评论(0编辑  收藏  举报