Python 2.7登录脚本问题排查:实现账号密码校验功能
修正后的Python 2.7登录脚本及问题分析
首先,咱们先理清你的核心需求:只有当用户名对应的文件存在,且输入的密码和文件中存储的密码完全匹配时,才允许登录;否则要么提示对应错误,要么在3次尝试后锁定账号。
先拆解下你当前脚本里的几个关键问题:
- 硬编码的密码提取逻辑(
Passwordl[10:])太脆弱,完全依赖"password :"这个字符串的固定长度,一旦格式有变动就直接失效 - 文件读取逻辑错误:你提供的用户文件内容是单行,但脚本尝试读取
Lines[1](第二行),这会直接抛出索引越界异常 - 重试次数计数有漏洞:当用户名存在但密码错误时,没有增加尝试次数,导致用户可以无限尝试密码
- 文件操作未正确关闭,存在资源泄漏风险
第一步:确保用户文件格式正确
先按照要求创建用户文件(比如test.txt),建议每行一个键值对,这样更易于解析:
name :test password :123321 admin :0
第二步:修正后的登录脚本
import os print "Hello to login - enter your credentials" login_success = False attempts = 0 max_attempts = 3 while not login_success and attempts < max_attempts: username = raw_input("Enter username: ") user_file = username + ".txt" # 检查用户文件是否存在 if os.path.isfile(user_file): # 使用with语句自动管理文件资源,避免泄漏 with open(user_file, "r") as f: lines = f.readlines() stored_password = None # 遍历文件行提取密码 for line in lines: line = line.strip() if line.startswith("password :"): # 分割键值对,提取冒号后的密码内容 stored_password = line.split(":", 1)[1].strip() break if stored_password is not None: password = raw_input("Enter password: ") if password == stored_password: login_success = True break else: print "Incorrect password." else: print "User file is missing password information." else: print "Username does not exist." attempts += 1 if attempts < max_attempts: print "You have {} attempts left.".format(max_attempts - attempts) if login_success: print "Welcome {}!".format(username) else: print "You've exceeded {} login attempts. User locked.".format(max_attempts)
关键修改点说明
- 文件资源安全:用
with open(...)替代直接打开文件,会自动关闭文件,避免资源泄漏问题 - 灵活的密码解析:遍历文件行查找密码项,用
split(":", 1)分割键值对,不再依赖固定字符串长度,兼容性更强 - 清晰的错误提示:区分"用户名不存在"、"密码错误"、"文件缺少密码"三种场景,用户体验更友好
- 严谨的重试计数:无论用户名是否存在,只要登录失败就增加尝试次数,严格限制最多3次尝试
- 可读性优化:把
login、att改成更清晰的login_success、attempts,代码逻辑更易懂
这样修改后,脚本就能准确实现你想要的逻辑:只有用户名和密码都验证通过时,才进入欢迎界面;否则根据情况提示错误,3次失败后锁定账号。
内容的提问来源于stack exchange,提问作者Nave Cohen
相关产品推荐
相关产品推荐

