新增内容包括: 1. 7个业务需求占位文档目录与README 2. 共享OA登录、钉钉机器人推送工具模块 3. 雇主险变更清单导出脚本 4. 考勤月报封存检查两个检查脚本 5. 重庆社保停保导入名单生成脚本
448 lines
17 KiB
Python
448 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: hr_login.py
|
||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||
|
||
如何在影刀中创建指令:
|
||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||
|
||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||
(本地开发时也兼容当前工作目录下的 .env);
|
||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||
|
||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||
LOGIN_URL=HR 登录页 URL
|
||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||
USERNAME=用户名
|
||
PASSWORD=密码
|
||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||
|
||
全局变量(在影刀流程中创建,此指令负责写入):
|
||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||
|
||
依赖(影刀「Python包管理」安装):
|
||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||
|
||
入口:
|
||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||
"""
|
||
import os
|
||
import json
|
||
import time
|
||
import random
|
||
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
from dotenv import load_dotenv
|
||
import requests
|
||
import cv2
|
||
import numpy as np
|
||
|
||
# ================== 共享路径(与 app 版统一) ==================
|
||
_APP_DATA_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation')
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||
|
||
|
||
def _load_shared_env():
|
||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||
if os.path.exists(SHARED_ENV_FILE):
|
||
load_dotenv(SHARED_ENV_FILE)
|
||
load_dotenv()
|
||
|
||
|
||
# ================== 配置 ==================
|
||
# 直接内置配置:影刀分享出去的脚本找不到 .env,登录参数直接写死
|
||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||
USERNAME = '37036273'
|
||
PASSWORD = '***REMOVED***'
|
||
|
||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||
|
||
LOGIN_BTN = "@id=login-btn"
|
||
ACCOUNT_INPUT = "@id=j_username"
|
||
PASSWORD_INPUT = "@id=j_password_2"
|
||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||
SLIDER_BTN = ".:v_rightBtn"
|
||
BG_IMG = ".imgBg"
|
||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||
|
||
RETRY_MAX = 5
|
||
TIMEOUT = 10
|
||
HEADLESS = False
|
||
|
||
|
||
def ensure_dir(path):
|
||
if path:
|
||
os.makedirs(path, exist_ok=True)
|
||
|
||
|
||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||
def save_browser_cookies(page):
|
||
cookies = page.cookies(all_domains=True)
|
||
if not cookies:
|
||
print("未获取到 Cookies,跳过保存")
|
||
return
|
||
ensure_dir(_SESSIONS_DIR)
|
||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||
|
||
|
||
def load_cookies():
|
||
if not os.path.exists(COOKIE_FILE):
|
||
return None
|
||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
# ================== 影刀全局变量 ==================
|
||
def _set_login_state(value):
|
||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||
try:
|
||
glv['login_state'] = value
|
||
print(f"已写入影刀全局变量 login_state={value}")
|
||
except Exception as e:
|
||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||
|
||
|
||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||
def _is_hr_session_valid():
|
||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||
|
||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||
"""
|
||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||
try:
|
||
cookies = load_cookies()
|
||
if not cookies:
|
||
return False
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
})
|
||
for c in cookies:
|
||
if c.get("domain") and "37du.co" in c["domain"]:
|
||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||
resp = session.post(validate_url, data={}, timeout=15)
|
||
if resp.status_code != 200:
|
||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||
return False
|
||
text = resp.text
|
||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||
except Exception as e:
|
||
print(f"API 校验 cookies 异常:{e}")
|
||
return False
|
||
|
||
|
||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||
def match_slider_dual(bg_bytes, slider_bytes):
|
||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||
if bg_img is None or slider_color is None:
|
||
raise RuntimeError("无法解码验证码图片")
|
||
|
||
bg_h, bg_w = bg_img.shape[:2]
|
||
x_offset, y_offset = 0, 0
|
||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||
alpha = slider_color[:, :, 3]
|
||
slider_rgb = slider_color[:, :, :3]
|
||
ys, xs = np.where(alpha > 0)
|
||
if len(ys) > 0:
|
||
y_min, y_max = np.min(ys), np.max(ys)
|
||
x_min, x_max = np.min(xs), np.max(xs)
|
||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||
x_offset, y_offset = x_min, y_min
|
||
else:
|
||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||
|
||
s_h, s_w = slider_rgb.shape[:2]
|
||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||
|
||
candidates = []
|
||
temp_result = result.copy()
|
||
for _ in range(6):
|
||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||
if max_val < 0.03:
|
||
break
|
||
candidates.append((max_val, max_loc))
|
||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||
temp_result[y0:y1, x0:x1] = -2.0
|
||
|
||
if not candidates:
|
||
raise RuntimeError("无有效滑块候选")
|
||
|
||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||
|
||
def region_whiteness(x, y, w, h):
|
||
roi = bg_img[y:y + h, x:x + w]
|
||
if roi.size == 0:
|
||
return 0.0
|
||
return float(np.all(roi > 200, axis=2).mean())
|
||
|
||
scored = []
|
||
for val, loc in candidates:
|
||
x, y = loc
|
||
if x <= s_w or x > right_limit:
|
||
continue
|
||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||
|
||
if scored:
|
||
scored.sort(key=lambda t: t[0], reverse=True)
|
||
best_val, best_loc = scored[0][1], scored[0][2]
|
||
else:
|
||
best_val, best_loc = candidates[0]
|
||
|
||
distance = best_loc[0] - x_offset
|
||
if distance < 0:
|
||
distance = 0
|
||
if distance + s_w > bg_w:
|
||
distance = bg_w - s_w
|
||
return distance
|
||
|
||
|
||
# ================== 轨迹生成与滑动 ==================
|
||
def generate_track(distance):
|
||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||
aim = distance + overshoot
|
||
steps = []
|
||
moved = 0
|
||
y = 0
|
||
while moved < aim:
|
||
remain = aim - moved
|
||
if remain > 80:
|
||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||
elif remain > 35:
|
||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||
elif remain > 12:
|
||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||
else:
|
||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||
if random.random() < 0.22:
|
||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||
else:
|
||
y = int(round(y * 0.6))
|
||
steps.append((dx, y, dt))
|
||
moved += dx
|
||
if overshoot > 0:
|
||
back = overshoot
|
||
while back > 0:
|
||
dx = -min(back, random.randint(1, 3))
|
||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||
back += dx
|
||
if random.random() < 0.65:
|
||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||
(1, 0, random.uniform(0.020, 0.050)),
|
||
(-1, 0, random.uniform(0.020, 0.050))])
|
||
return steps
|
||
|
||
|
||
def perform_slide(page, btn, distance_css):
|
||
if distance_css <= 0:
|
||
return False
|
||
mid = btn.rect.midpoint
|
||
steps = generate_track(distance_css)
|
||
try:
|
||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||
duration=random.uniform(0.25, 0.60))
|
||
time.sleep(random.uniform(0.18, 0.45))
|
||
page.actions.hold(on_ele=btn)
|
||
time.sleep(random.uniform(0.12, 0.28))
|
||
for dx, dy, dt in steps:
|
||
if dx == 0 and dy == 0:
|
||
time.sleep(dt)
|
||
else:
|
||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||
time.sleep(random.uniform(0.10, 0.26))
|
||
page.actions.release()
|
||
return True
|
||
except Exception as e:
|
||
print(f"拖拽异常:{e}")
|
||
return False
|
||
|
||
|
||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||
def handle_captcha(page):
|
||
for retry in range(RETRY_MAX):
|
||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||
try:
|
||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||
if not container:
|
||
print("验证码容器未出现")
|
||
continue
|
||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||
slider_ele = container.ele(SLIDER_IMG)
|
||
if not bg_ele or not slider_ele:
|
||
print("找不到背景图/滑块小图元素")
|
||
continue
|
||
if slider_ele.tag != 'img':
|
||
inner = slider_ele.ele('tag:img')
|
||
if inner:
|
||
slider_ele = inner
|
||
try:
|
||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||
time.sleep(0.2)
|
||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||
time.sleep(0.2)
|
||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||
except Exception:
|
||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||
continue
|
||
|
||
if not bg_screenshot or not slider_screenshot:
|
||
print("截图数据为空")
|
||
continue
|
||
|
||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||
distance_css = distance_phys / dpr
|
||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||
|
||
btn = page.ele(SLIDER_BTN)
|
||
if btn and perform_slide(page, btn, distance_css):
|
||
time.sleep(2)
|
||
if SUCCESS_KEYWORD in page.url:
|
||
return True
|
||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||
return True
|
||
time.sleep(2)
|
||
except Exception as e:
|
||
print(f"异常:{e}")
|
||
time.sleep(1)
|
||
return False
|
||
|
||
|
||
# ================== 登录主流程 ==================
|
||
def _do_login():
|
||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||
co = ChromiumOptions()
|
||
if HEADLESS:
|
||
co.headless()
|
||
page = ChromiumPage(co)
|
||
try:
|
||
page.get(LOGIN_URL)
|
||
time.sleep(2)
|
||
|
||
if SUCCESS_KEYWORD in page.url:
|
||
print("已登录")
|
||
save_browser_cookies(page)
|
||
return True
|
||
|
||
account = page.ele(ACCOUNT_INPUT)
|
||
if not account:
|
||
print("找不到账号输入框")
|
||
return False
|
||
account.clear()
|
||
account.input(USERNAME)
|
||
time.sleep(0.5)
|
||
|
||
pwd = page.ele(PASSWORD_INPUT)
|
||
if not pwd:
|
||
print("找不到密码输入框")
|
||
return False
|
||
pwd.clear()
|
||
pwd.input(PASSWORD)
|
||
time.sleep(0.5)
|
||
|
||
login_btn = page.ele(LOGIN_BTN)
|
||
if not login_btn:
|
||
print("找不到登录按钮")
|
||
return False
|
||
login_btn.click()
|
||
time.sleep(3)
|
||
|
||
if SUCCESS_KEYWORD in page.url:
|
||
print("登录成功(无滑块)")
|
||
save_browser_cookies(page)
|
||
return True
|
||
|
||
if handle_captcha(page):
|
||
print("登录成功(验证通过)")
|
||
save_browser_cookies(page)
|
||
return True
|
||
print("登录失败")
|
||
return False
|
||
finally:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def ensure_login(force=False):
|
||
"""
|
||
确保存在有效的 HR 登录态并缓存 cookies。
|
||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||
"""
|
||
_load_shared_env()
|
||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||
_set_login_state(False)
|
||
|
||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||
if not (USERNAME and PASSWORD):
|
||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||
|
||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||
if not force and _is_hr_session_valid():
|
||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||
_set_login_state(True)
|
||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||
"message": "复用缓存登录态", "relogin": False}
|
||
|
||
ok = _do_login()
|
||
if ok:
|
||
_set_login_state(True)
|
||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||
|
||
|
||
# ================== 影刀自定义指令入口 ==================
|
||
def main(args):
|
||
"""
|
||
影刀自定义指令「37duHR登录」调用入口。
|
||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||
返回: dict {success, cookie_path, message, relogin}
|
||
"""
|
||
if not args:
|
||
args = {}
|
||
force = bool(args.get("force", False))
|
||
try:
|
||
return ensure_login(force=force)
|
||
except Exception as e:
|
||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||
"message": f"登录过程异常:{e}", "relogin": False}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
result = main({"force": False})
|
||
print("最终结果:", result)
|