Python案例如何验证验证码正误?

wen python案例 9

本文目录导读:

Python案例如何验证验证码正误?

  1. 纯字符串验证码(最基础)
  2. 图片验证码(使用PIL/Tesseract)
  3. 验证码有效期验证
  4. 滑动验证码验证
  5. 防刷机制
  6. 最佳实践建议

在Python中验证验证码正误,通常有几种场景,我分别给出案例和思路:

纯字符串验证码(最基础)

这是最简单的场景,通常用于后端校验用户输入的验证码是否与生成的验证码一致。

# 生成验证码(通常存session)
import random
import string
def generate_captcha(length=4):
    """生成随机验证码"""
    chars = string.ascii_letters + string.digits  # 字母+数字
    captcha = ''.join(random.choice(chars) for _ in range(length))
    return captcha
# 验证验证码(忽略大小写)
def verify_captcha(user_input, saved_captcha):
    """验证用户输入的验证码是否正确"""
    return user_input.lower() == saved_captcha.lower()
# 示例
if __name__ == "__main__":
    saved = generate_captcha()
    print(f"生成的验证码: {saved}")
    user_input = input("请输入验证码: ")
    if verify_captcha(user_input, saved):
        print("✅ 验证码正确!")
    else:
        print("❌ 验证码错误!")

图片验证码(使用PIL/Tesseract)

当验证码是一张图片时,需要用OCR识别:

from PIL import Image
import pytesseract
def verify_image_captcha(image_path):
    """识别图片验证码"""
    # 打开图片
    img = Image.open(image_path)
    # 预处理图片(提高识别率)
    img = img.convert('L')  # 灰度化
    img = img.point(lambda x: 0 if x < 128 else 255)  # 二值化
    # OCR识别
    captcha_text = pytesseract.image_to_string(img, config='--psm 7').strip()
    return captcha_text
def verify_user_input(image_path, user_input):
    """验证用户输入是否匹配图片验证码"""
    recognized = verify_image_captcha(image_path)
    print(f"识别出的验证码: {recognized}")
    return user_input.lower() == recognized.lower()
# 示例
# verify_user_input('captcha.png', 'ABC123')

验证码有效期验证

在实际系统中,验证码通常有过期时间:

import time
from datetime import datetime, timedelta
class CaptchaValidator:
    def __init__(self):
        self.captchas = {}  # 存储验证码及其创建时间
    def generate_and_store(self, session_id, length=4):
        """生成验证码并存储(带时间戳)"""
        import random
        import string
        captcha = ''.join(random.choice(string.digits) for _ in range(length))
        self.captchas[session_id] = {
            'code': captcha,
            'created_at': datetime.now()
        }
        return captcha
    def verify(self, session_id, user_input, expire_minutes=5):
        """验证验证码(带过期时间)"""
        if session_id not in self.captchas:
            return False, "验证码不存在"
        captcha_data = self.captchas[session_id]
        # 检查是否过期
        if datetime.now() - captcha_data['created_at'] > timedelta(minutes=expire_minutes):
            del self.captchas[session_id]  # 清理过期验证码
            return False, "验证码已过期"
        # 验证内容
        if user_input == captcha_data['code']:
            del self.captchas[session_id]  # 验证成功后删除
            return True, "验证成功"
        else:
            return False, "验证码错误"
# 使用示例
validator = CaptchaValidator()
session = "user_session_123"
code = validator.generate_and_store(session)
print(f"验证码已发送到用户: {code}")
# 用户输入验证
result, msg = validator.verify(session, "1234")
print(f"验证结果: {msg}")

滑动验证码验证

使用第三方服务(如极验、腾讯防水墙):

import requests
import json
class SlideCaptchaValidator:
    """滑动验证码验证(以GEETEST为例)"""
    def __init__(self, captcha_id, private_key):
        self.captcha_id = captcha_id
        self.private_key = private_key
    def validate(self, geetest_challenge, geetest_validate, geetest_seccode):
        """验证滑动验证码"""
        url = "https://api.geetest.com/validate.php"
        params = {
            'gt': self.captcha_id,
            'challenge': geetest_challenge,
            'validate': geetest_validate,
            'seccode': geetest_seccode,
            'json_format': 1
        }
        response = requests.get(url, params=params)
        result = response.json()
        return result.get('status') == 'success'
# 使用示例
# validator = SlideCaptchaValidator('your_captcha_id', 'your_private_key')
# result = validator.validate(challenge, validate, seccode)

防刷机制

防止暴力破解的验证码逻辑:

from collections import defaultdict
import time
class SecureCaptchaValidator:
    def __init__(self):
        self.attempts = defaultdict(list)  # 存储尝试记录
        self.max_attempts = 5  # 最大尝试次数
        self.lockout_time = 300  # 锁定时间(秒)
    def check_attempts(self, user_id):
        """检查用户尝试次数"""
        now = time.time()
        user_attempts = self.attempts[user_id]
        # 清理过期的尝试记录
        user_attempts = [t for t in user_attempts if now - t < self.lockout_time]
        self.attempts[user_id] = user_attempts
        if len(user_attempts) >= self.max_attempts:
            return False, "尝试次数过多,请稍后再试"
        return True, "可以继续尝试"
    def record_attempt(self, user_id):
        """记录一次尝试"""
        self.attempts[user_id].append(time.time())
    def verify_with_ratelimit(self, user_id, user_input, saved_captcha):
        """带频率限制的验证码验证"""
        # 检查频率限制
        can_proceed, msg = self.check_attempts(user_id)
        if not can_proceed:
            return False, msg
        # 记录本次尝试
        self.record_attempt(user_id)
        # 验证码校验
        if user_input.lower() == saved_captcha.lower():
            self.attempts[user_id] = []  # 成功后重置尝试记录
            return True, "验证成功"
        else:
            return False, "验证码错误"
# 使用示例
validator = SecureCaptchaValidator()
for i in range(6):  # 模拟多次尝试
    result, msg = validator.verify_with_ratelimit("user123", "wrong", "1234")
    print(f"第{i+1}次尝试: {msg}")

最佳实践建议

  1. 服务端验证:验证码验证必须在服务端完成,前端只是辅助
  2. 使用HTTPS:防止中间人攻击
  3. 一次有效:验证码使用后立即失效
  4. 设置过期时间:通常5-10分钟有效
  5. 限制尝试次数:防止暴力破解
  6. 忽略大小写:提高用户体验

这些案例涵盖了从简单到复杂的验证码验证场景,可以根据实际需求选择合适的方案。

抱歉,评论功能暂时关闭!