用户名和密码验证在Python中可通过多种方式实现,以下是常见方法及示例代码:
一、简单验证(明文比对)
适用于教学或非敏感场景,直接将用户输入与预设密码对比。
users = { "alice": "password123", "bob": "secretpassword" }
def authenticate(username, password):
return username in users and users[username] == password
username = input("请输入用户名: ")
password = input("请输入密码: ")
if authenticate(username, password):
print("身份验证成功!")
else:
print("身份验证失败。")
二、带锁定机制的验证
通过记录错误次数实现账户锁定,防止暴力破解。
# 锁定次数阈值
MAX_ATTEMPTS = 3
def authenticate(username, password):
with open("login_lock.txt", "r") as f:
locked_users = set(line.strip() for line in f)
if username in locked_users:
print("用户名已被锁定,请联系管理员。")
return False
with open("login.txt", "r") as f:
for line in f:
stored_username, stored_password = line.strip().split(":")
if username == stored_username and password == stored_password:
return True
return False
username = input("请输入用户名: ")
password = input("请输入密码: ")
attempts = 0
while attempts < MAX_ATTEMPTS:
if authenticate(username, password):
print("欢迎使用系统!")
break
else:
attempts += 1
print(f"错误次数:{attempts}/{MAX_ATTEMPTS},账户已被锁定。")
三、使用哈希和盐值保护密码
实际应用中,密码应加密存储,避免明文风险。
import hashlib
import os
# 假设用户数据存储在字典中
users = { "alice": "password123", "bob": "secretpassword" }
def hash_password(password):
salt = os.urandom(16).hex()
return hashlib.sha256((salt + password).encode()).hexdigest()
def authenticate(username, password):
if username in users:
stored_hash = users[username]
return hash_password(password) == stored_hash
return False
username = input("请输入用户名: ")
password = input("请输入密码: ")
if authenticate(username, password):
print("登录成功!")
else:
print("密码错误。")
四、结合文件读写的完整示例
实现注册、登录及锁定功能,适用于小型应用。
# 假设用户数据存储在login.txt文件中
def register(username, password):
with open("login.txt", "a") as f:
f.write(f"{username}:{hash_password(password)}\n")
def authenticate(username, password):
with open("login.txt", "r") as f:
for line in f:
stored_username, stored_hash = line.strip().split(":")
if username == stored_username and hash_password(password) == stored_hash: