训练1:

模拟登陆:

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

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

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

login2.py:

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author : Wang Yue import sys,hashlib,getpass,time #定义用户类
class real_user(object):
real_name=''#用户名
real_pwd=''#密码
login_count=0 #登录次数
lock_time=0 #锁定时间
#重写构造函数,用于初始化用户类实例
def __init__(self,real_name,real_pwd):
self.real_name=real_name
self.real_pwd=real_pwd
#属性设定方法
def set_lock(self,lt):
self.lock_time=lt def get_login_count(self):
return self.login_count #定义业务方法,用于锁定自身用户实例的方法
def lock_me(self,seconds):
self.lock_time=seconds
lock_info=self.real_name + "," + str(self.lock_time) + "\n"
return lock_info
#定义业务方法,用于解锁自身用户实例
def unlock_me(self,u_name):#lock_time float
if u_name == self.real_name and time.time() >= self.lock_time:
self.lock_time = 0
return True
else:
return False #单独封装的函数,主函数中会使用到的方法,公共性的,对于主函数透明
#从文件(数据源)中,将已经存在的用户信息,写为字符串数组,返回该数组
def get_file_line(file,mode_file):
userlist = []
with open(file,mode=mode_file,encoding='utf-8') as filedb:
filedb.flush()
filedb.seek(0)
fileline=filedb.readline()
while fileline:
userlist.append(fileline)
fileline=filedb.readline()
return userlist #将信息回写到文件,主函数中用于写黑名单
def input_line_file(file,info):#info is a list
with open(file,mode="a+",encoding="utf-8") as filedb:
for info_line in info:
filedb.write(info_line + "\n") #将信息从文件中删除,含有信息的行会被删除
def delete_line_file(file,info):
with open(file,mode="w+",encoding="utf-8") as filedb:
filedb.flush()
filedb.seek(0)
for line_one in filedb.readlines():
if info in line_one:
line_info=line_one.split()
if line_info[0] == info:
continue
filedb.write(line_one) #校验登录,参数:登录的用户名,密码,真是存在的用户实例list
#用户名密码,检查锁定状态
#返回值:登录成功,当前锁定。(用户名压根不存在的话,在主函数就过滤掉了)
def verify_me(u_name,u_pwd,user):
if user.lock_time != 0:
return "fuck you,fuck off"
if time.time()>=user.lock_time:
user.lock_time=0
if user.real_name == u_name:
user.login_count +=1
if user.real_name == u_name and user.real_pwd == u_pwd:
user.login_count = 0
user.lock_time = 0
return "sucess"
else:
return "retry once....." #获得MD5,密码在文件中存放时是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 #主函数
if __name__ == '__main__':
userlist=get_file_line("user_db.doo","r") #获取用户信息,存成信息list
locklist=get_file_line("lock_db.doo","r") #获取黑名单信息,存成信息list
user=[] #定义用户实例数组 #初始化全部用户实例,使用用户类的构造函数
for user_line in userlist:
name_pwd=user_line.split("::++++::")
name=name_pwd[0].strip()
pwd=name_pwd[1].strip()
user.append(real_user(name,pwd)) #遍历用户实例数组,将锁定属性赋值
for lock_inf in locklist:
lock_info=lock_inf.strip()
if lock_info =='':
continue
lockif=lock_info.split(',')
for user_ok in user:
if user_ok.real_name==lockif[0]:
user_ok.set_lock(float(lockif[1].strip())) #以下开始正式业务
count = 0 #用于记录登录次数
while True:
#输入用户名密码,并将密码MD5
print("hello let try login")
username=input("username:")
passinput=input("password:")
passwd = get_md5_enc(passinput) #从用户类实例list中,确定用户行为:用户名是否正确?密码是否正确?
for user_one in user:
#用户名不正确,3次,提示需要注册,程序结束
if user_one.real_name !=username:
if count >2:
print("you need reg.....")
sys.exit(0)
continue #用户名正确,密码情况:
check_login=verify_me(username,passwd,user_one)
#密码正确,登录成功
if check_login =="sucess":
print("hello:{_name},login success!!!!".format(_name=username))
delete_line_file("lock_db.doo",username)
sys.exit(0)
#密码不正确,该用户实例的登录次数+1,避免仅提供三次输入用户名密码就结束的情况,不然中途换了用户名,就出bug了
#用户名正确时,用户登录次数超过3次,将被锁定5分钟。
elif user_one.get_login_count() > 2 and user_one.real_name == username:
lock_time=time.time()+300
lock_info=user_one.lock_me(lock_time)
lockjj=[]
lockjj.append(lock_info)
input_line_file("lock_db.doo",lockjj)
print("fuck you,lock you 5m!!!!")
sys.exit(0)
#登录状态为锁定的话,就结束程序
elif check_login =="fuck you,fuck off":
print("fuck you,fuck off:{_name}.you were locked".format(_name=username))
sys.exit(0)
#解锁用户:锁定时间算法为(锁定发生时,增加300秒),当前时间>=锁定的时间,即可解锁
elif user_one.lock_time <= time.time() and user_one.real_name==username:
user_one.unlock_me(username)
delete_line_file("lock_db.doo",username)
continue
#判定用户名不正确的使用登录次数,超过3次就结束
elif count <2:
count +=1
break
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

python3.x Day1 用户登录程序练习的更多相关文章

  1. 运用String类实现一个模拟用户登录程序

    package Test; import java.util.Scanner; // 模拟用户登录程序 // 思路: // 1.用两个String类分别接收用户名和密码 // 2.判断输入的用户名和密 ...

  2. Python入门-用户登录程序升级版

    编写登陆接口 基础需求: 让用户输入用户名密码 认证成功后显示欢迎信息 输错三次后退出程序 升级需求: 可以支持多个用户登录 (提示,通过列表存多个账户信息) 用户3次认证失败后,退出程序,再次启动程 ...

  3. Python阶段复习 - part 4 - 用户登录程序

    简易版: #!/usr/bin/env python # _*_ coding:UTF-8 _*_ # __auth__:Dahlhin import sys userinfo = r'userinf ...

  4. 基于Struts2的用户登录程序

    基本步骤: 1.新建Java工程,File>New>Project>Web>Dynamic Web Project,并将工程命名为:Struts2_Demo 2.导入strut ...

  5. python3.0 模拟用户登录,三次错误锁定

    # -*- coding:utf-8 -*- #需求模拟用户登录,超过三次错误锁定不允许登陆     count = 0   #realname passwd Real_Username = &quo ...

  6. 第三篇python用户登录程序实现

    需求: 1.通过注册输入用户名和密码 2.能够验证用户名和密码是否正确 3.限制输入一定错误次数后退出程序 4.利用格式化输出方式输出信息 分析: 使用username=input()和passwor ...

  7. Python入门-用户登录程序

    _flag = Falsecount = 0users = [['ziv', '123'], ['alex', '12345']]while count < 3: username = inpu ...

  8. Python之路 day1 用户登录多次被锁定

    编写登陆接口: 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定 #Author:ersa import getpass,os,sys #读取账户信息到内存中 try: accounts_fil ...

  9. python程序—用户登录

    编写一个用户登录程序: 1.登录成功显示登录页面 2.登录失败,显示密码错误,并且显示错误几次 3.登录失败三次,退出程序 username= 'root' passwd= ' count= prin ...

随机推荐

  1. 8-15 globalCompositeOperation阶段练习二

    8-15 globalCompositeOperation阶段练习二 <!DOCTYPE html> <html lang="zh-cn"> <hea ...

  2. 4.8 Using Ambiguous Grammars

    4.8 Using Ambiguous Grammars It is a fact that every ambiguous grammar fails to be LR and thus is no ...

  3. bzoj1509

    树的直径 我先开始以为是个图,想想并不知道什么求图的直径的方法,结果是棵树 那么直觉告诉我们是在直径上面,实际上就是直径+min(i->u,i->v),扫一遍就行了 #include< ...

  4. window系统 查看端口 被哪个进程占用了

    一.在windows命令行窗口下执行:运行--cmdC:\>netstat -aon|findstr "8080" TCP     127.0.0.1:80       0. ...

  5. mybatis中各种数据的映射类型

    Mybatis对应的java和数据库的数据类型,最后有图片 Mybatis                                  java                          ...

  6. 乐搏讲自动化测试- Python环境搭建(7)

    Python的下载和安装 Python可应用于多平台包括 Linux 和 Mac OS X.你可以通过终端窗口输入 "python" 命令来查看本地是否已经安装Python以及Py ...

  7. Maven之项目搭建与第一个helloworld(多图)

    这次记录第一个搭建一个maven的helloworld的过程. 转载 1.搭建web工程肯定得new 一个 maven工程,假如project中没有直接看到maven工程,那么选择Other,然后在W ...

  8. json和Jsonp 使用总结(1)

    1.Json的使用 $.getJSON("subPreview", { jsonDatas: JSON.stringify(jsonData) }, function(data) ...

  9. Lightoj 1020 - A Childhood Game (博弈)

    题目链接: 1020 - A Childhood Game 题目描述: Alice和Bob在玩弹珠游戏,两人轮流拿走弹珠,每次只能拿走一个或者两个,当Alice作为先手时谁拿走最后一个就是输家,而Bo ...

  10. 莫队算法 Gym - 100496D Data Mining

    题目传送门 /* 题意:从i开始,之前出现过的就是之前的值,否则递增,问第p个数字是多少 莫队算法:先把a[i+p-1]等效到最前方没有它的a[j],问题转变为求[l, r]上不重复数字有几个,裸莫队 ...