Files
jwxt/app/jwxt_login.py
T

448 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
教务系统登录脚本 - 使用 ddddocr 识别验证码
"""
import os
import time
import re
import requests
import ddddocr
from pathlib import Path
import json
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
# 从统一配置读取默认地址(运行时动态获取当前最优地址)
from app.url_manager import get_base_url
# OCR 模型加载耗时(数百 ms~秒级),模块级单例复用
_OCR_SINGLETON = None
def _get_ocr():
global _OCR_SINGLETON
if _OCR_SINGLETON is None:
_OCR_SINGLETON = ddddocr.DdddOcr()
return _OCR_SINGLETON
class JWXTLogin:
"""教务系统登录类"""
def __init__(self, base_url=None):
"""
初始化
:param base_url: 教务系统基础URL,默认从 settings.BASE_URL 读取
"""
self.base_url = (base_url or get_base_url()).rstrip('/')
from app.school_manager import list_schools, requires_captcha
from app.url_manager import current_school_id
active_school = current_school_id()
if active_school:
self.requires_captcha = requires_captcha(active_school)
else:
self.requires_captcha = next((s.get('requires_captcha', True)
for s in list_schools() if self.base_url in s['urls']), True)
from urllib.parse import urlparse
parsed = urlparse(self.base_url)
self._origin = f"{parsed.scheme}://{parsed.netloc}"
self.session = requests.Session()
self.ocr = _get_ocr() if self.requires_captcha else None
# 设置请求头
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
})
def get_captcha(self):
"""
获取验证码图片
:return: 验证码图片内容和图片URL
"""
captcha_url = f"{self.base_url}/kaptcha"
params = {'time': int(time.time() * 1000)}
response = self.session.get(captcha_url, params=params, timeout=(5, 15))
response.raise_for_status()
return response.content, f"{captcha_url}?{params['time']}"
def get_rsa_public_key(self):
"""
获取RSA公钥
:return: modulus, exponent
"""
url = f"{self.base_url}/xtgl/login_getPublicKey.html"
params = {'time': int(time.time() * 1000)}
response = self.session.get(url, params=params, timeout=(5, 15))
response.raise_for_status()
data = response.json()
return data['modulus'], data['exponent']
def rsa_encrypt_password(self, password, modulus, exponent):
"""
使用RSA公钥加密密码
:param password: 明文密码
:param modulus: RSA模数
:param exponent: RSA指数
:return: Base64编码的加密密码
"""
# 将base64的modulus和exponent转换为数字
modulus_int = int.from_bytes(base64.b64decode(modulus), byteorder='big')
exponent_int = int.from_bytes(base64.b64decode(exponent), byteorder='big')
# 创建RSA公钥对象
key = RSA.construct((modulus_int, exponent_int))
# 加密密码
cipher = PKCS1_v1_5.new(key)
encrypted_password = cipher.encrypt(password.encode('utf-8'))
# 转换为base64
return base64.b64encode(encrypted_password).decode('utf-8')
def recognize_captcha(self, image_data):
"""
使用 ddddocr 识别验证码
:param image_data: 验证码图片二进制数据
:return: (识别结果, 耗时ms)
"""
try:
t0 = time.perf_counter()
result = self.ocr.classification(image_data)
ms = int((time.perf_counter() - t0) * 1000)
return result, ms
except Exception as e:
print(f"验证码识别失败: {e}")
return None, 0
@staticmethod
def _validate_captcha_format(code):
"""
校验验证码格式:必须为6位字母+数字组合
:param code: OCR 识别结果
:return: True 格式正确, False 格式错误
"""
if not code:
return False
import re
return bool(re.fullmatch(r'[a-zA-Z0-9]{6}', code))
def login(self, username, password, captcha_code=None):
"""
登录教务系统(单次尝试,不含重试)
:param username: 用户名
:param password: 密码
:param captcha_code: 验证码(如果为None则自动获取并识别)
:return: {
'success': bool,
'message': str,
'ocr_ms': int, # OCR 识别耗时(ms)
'total_ms': int, # 登录总耗时(ms)
'steps': { # 各步骤耗时(ms)
'get_page_ms': int,
'captcha_ms': int,
'get_rsa_ms': int,
'encrypt_ms': int,
'post_login_ms': int,
}
}
"""
t_start = time.perf_counter()
steps = {}
# 先访问登录页面获取csrftoken(必须在获取验证码之前,否则登录页会刷新验证码session)
print("正在获取登录页面...")
t0 = time.perf_counter()
login_page_url = f"{self.base_url}/xtgl/login_slogin.html"
response = self.session.get(login_page_url, timeout=(5, 15))
steps['get_page_ms'] = int((time.perf_counter() - t0) * 1000)
# 如果没有提供验证码,则自动获取并识别(必须在访问登录页之后)
ocr_ms = 0
if captcha_code is None and self.requires_captcha:
max_ocr_retries = 2
for ocr_attempt in range(1, max_ocr_retries + 1):
print(f"正在获取验证码 (第{ocr_attempt}次)...")
t0 = time.perf_counter()
captcha_img, _ = self.get_captcha()
steps['captcha_ms'] = int((time.perf_counter() - t0) * 1000)
print(f"正在识别验证码...")
raw_code, ocr_ms = self.recognize_captcha(captcha_img)
print(f"识别到的验证码: {raw_code}")
if not raw_code:
print(f"验证码识别失败,准备重试...")
continue
if self._validate_captcha_format(raw_code):
captcha_code = raw_code
print(f"验证码格式校验通过: {captcha_code}")
break
else:
print(f"验证码格式异常(期望6位字母数字,实际={len(raw_code) if raw_code else 0}位'{raw_code}'), 重新识别...")
captcha_code = None
if not captcha_code:
return {
'success': False,
'message': f'验证码识别失败(已尝试{max_ocr_retries}次OCR)',
'ocr_ms': ocr_ms,
'total_ms': int((time.perf_counter() - t_start) * 1000),
'steps': steps,
}
else:
steps['captcha_ms'] = 0
# 从页面中提取csrftoken
csrftoken_match = re.search(r'<input[^>]*name="csrftoken"[^>]*value="([^"]+)"', response.text)
csrftoken = csrftoken_match.group(1) if csrftoken_match else ''
# 获取RSA公钥并加密密码
print("正在获取RSA公钥...")
t0 = time.perf_counter()
modulus, exponent = self.get_rsa_public_key()
steps['get_rsa_ms'] = int((time.perf_counter() - t0) * 1000)
print("正在加密密码...")
t0 = time.perf_counter()
encrypted_password = self.rsa_encrypt_password(password, modulus, exponent)
steps['encrypt_ms'] = int((time.perf_counter() - t0) * 1000)
print("密码加密完成")
# 构造登录表单数据
login_url = f"{self.base_url}/xtgl/login_slogin.html"
data = {
'yhm': username,
'mm': encrypted_password, # 使用加密后的密码
'yzm': captcha_code or '',
'csrftoken': csrftoken,
'language': 'zh_CN',
'dlmmsfknt': '0',
'ydappsfbldlzt': '0',
'yzcskz': '-1',
'mmsfjm': '1', # 密码需要加密
'mmsrddcshkzfs': '0',
'dlsbsdsj': '3',
}
# 添加时间戳
login_url_with_time = f"{login_url}?time={int(time.time() * 1000)}"
print(f"正在登录用户: {username}")
t0 = time.perf_counter()
response = self.session.post(
login_url_with_time,
data=data,
allow_redirects=False,
timeout=(5, 15)
)
steps['post_login_ms'] = int((time.perf_counter() - t0) * 1000)
total_ms = int((time.perf_counter() - t_start) * 1000)
# 检查是否登录成功
# 注意: 服务器可能返回二次重定向,第一跳是登录页,第二跳才是首页
if response.status_code == 302:
location = response.headers.get('Location', '')
print(f"第一跳重定向到: {location}")
# 直接成功的标志
if 'index_initMenu.html' in location or 'auth_loginSuccess.html' in location:
print("[OK] 登录成功!")
return {'success': True, 'message': '登录成功', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
# 第一跳回到登录页,可能是二次重定向(实际已登录)
if 'login_slogin.html' in location or location.endswith('/login_slogin.html'):
# 跟随第二跳,看是否跳到首页
# 注意:Location 已经包含 /jwglxt path,所以用 origin(不含路径)拼接
second_url = location if location.startswith('http') else f"{self._origin}{location}"
r2 = self.session.get(second_url, allow_redirects=False, timeout=(5, 15))
location2 = r2.headers.get('Location', '')
print(f"第二跳重定向到: {location2}")
if 'index_initMenu.html' in location2 or 'auth_loginSuccess.html' in location2:
print("[OK] 登录成功! (二次重定向)")
return {'success': True, 'message': '登录成功', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
print(f"[FAIL] 登录失败,重定向到: {location}")
return {'success': False, 'message': f'登录失败: {location}', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
elif response.status_code == 200:
print("[FAIL] 登录失败,返回了登录页面")
# 尝试查找错误信息
if '用户名或密码不正确' in response.text:
msg = '用户名或密码不正确'
elif '验证码错误' in response.text or '验证码不正确' in response.text:
msg = '验证码错误'
elif '密码已到期' in response.text or '修改密码' in response.text or '密码过期' in response.text:
# 密码到期:重试无意义,标记 stop_retry 让上层立即终止
msg = '密码已到期,请修改密码后重试'
print(f"错误: {msg}")
return {'success': False, 'message': msg, 'stop_retry': True,
'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
else:
msg = '登录失败'
print(f"错误: {msg}")
return {'success': False, 'message': msg, 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
else:
print(f"[FAIL] 登录失败,状态码: {response.status_code}")
return {'success': False, 'message': f'登录失败(状态码{response.status_code})', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
def login_with_retry(self, username, password, max_retries=3):
"""
登录教务系统(含重试)
:param username: 用户名
:param password: 密码
:param max_retries: 最大重试次数
:return: {
'success': bool,
'message': str,
'timing': {
'attempts': int, # 尝试次数
'total_ms': int, # 总耗时
'ocr_ms': int, # 最后一次OCR耗时
'ocr_avg_ms': int, # 平均OCR耗时(attempts>1时有值)
}
}
"""
t_start = time.perf_counter()
ocr_times = []
for attempt in range(1, max_retries + 1):
print(f"\n尝试第 {attempt}/{max_retries} 次登录...")
result = self.login(username, password)
if result.get('ocr_ms'):
ocr_times.append(result['ocr_ms'])
if result['success']:
total_ms = int((time.perf_counter() - t_start) * 1000)
return {
'success': True,
'message': result['message'],
'timing': {
'attempts': attempt,
'total_ms': total_ms,
'ocr_ms': result['ocr_ms'],
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
}
}
if attempt < max_retries:
print(f"第 {attempt} 次登录失败: {result['message']}, 正在重试...")
total_ms = int((time.perf_counter() - t_start) * 1000)
return {
'success': False,
'message': f'登录失败(已尝试{max_retries}次): {result["message"]}',
'timing': {
'attempts': max_retries,
'total_ms': total_ms,
'ocr_ms': ocr_times[-1] if ocr_times else 0,
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
}
}
def save_session(self):
"""
保存会话信息到文件
"""
# 保存 Cookie 到文件
with open(COOKIE_JAR_FILE, 'w') as f:
for cookie in self.session.cookies:
f.write(f"{cookie.name}={cookie.value}\n")
# 保存会话信息到 JSON 文件
session_info = {
'cookies': dict(self.session.cookies),
'headers': dict(self.session.headers),
}
with open(SESSION_FILE, 'w', encoding='utf-8') as f:
json.dump(session_info, f, ensure_ascii=False, indent=2)
print(f"会话已保存到 {SESSION_FILE} 和 {COOKIE_JAR_FILE}")
def load_session(self):
"""
从文件加载会话信息
:return: 是否加载成功
"""
if not os.path.exists(SESSION_FILE):
print(f"会话文件不存在: {SESSION_FILE}")
return False
try:
with open(SESSION_FILE, 'r', encoding='utf-8') as f:
session_info = json.load(f)
# 恢复 cookies
self.session.cookies.update(session_info.get('cookies', {}))
print("会话加载成功")
return True
except Exception as e:
print(f"会话加载失败: {e}")
return False
def test_session(self):
"""
测试会话是否有效
:return: 会话是否有效
"""
test_url = f"{self.base_url}/xtgl/index_initMenu.html"
try:
response = self.session.get(test_url, allow_redirects=False, timeout=(5, 15))
return response.status_code == 200
except:
return False
def main():
"""主函数"""
print("=" * 50)
print("教务系统登录脚本")
print("=" * 50)
# 创建登录实例
login = JWXTLogin()
# 尝试加载已有会话
if os.path.exists(SESSION_FILE):
print("\n检测到已有会话文件,正在测试...")
if login.load_session():
if login.test_session():
print("[OK] 会话有效,无需重新登录")
return
else:
print("[FAIL] 会话已失效,需要重新登录")
# 输入用户名和密码
username = input("\n请输入用户名: ").strip()
password = input("请输入密码: ").strip()
if not username or not password:
print("用户名和密码不能为空!")
return
# 登录(含重试)
result = login.login_with_retry(username, password, max_retries=3)
if result['success']:
login.save_session()
t = result['timing']
print(f"\n[OK] 登录完成! 尝试 {t['attempts']} 次, 总耗时 {t['total_ms']}ms")
if t['ocr_avg_ms']:
print(f"OCR 平均耗时: {t['ocr_avg_ms']}ms")
else:
print(f"\n[FAIL] {result['message']}")
if __name__ == "__main__":
main()