from flask import Flask, request, jsonify import time import os import threading import json import subprocess app = Flask(__name__) # 全局防重锁状态 IS_RUNNING_CHUSHI = False GLOBAL_LOCK = threading.Lock() BASE_DIR = "/data" LOG_FILE = os.path.join(BASE_DIR, "success_results.txt") def run_chushi_py(): global IS_RUNNING_CHUSHI with GLOBAL_LOCK: if IS_RUNNING_CHUSHI: print("[SKIP] 初始.py 正在运行,跳过本次触发", flush=True) return IS_RUNNING_CHUSHI = True print("[START] 开始执行 初始.py", flush=True) try: # 🔴 关键:使用 Popen 实时捕获子进程输出 proc = subprocess.Popen( ["python3", "-u", "初始.py"], # -u 保证子进程实时输出 stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1 ) # 🔴 实时打印 stdout(正常日志) print(f"[初始.py 输出] 开始接收日志", flush=True) for line in iter(proc.stdout.readline, ""): if line.strip(): # 避免打印空行 print(f"[初始.py] {line.strip()}", flush=True) # 🔴 实时打印 stderr(错误日志) for line in iter(proc.stderr.readline, ""): if line.strip(): print(f"[初始.py ERROR] {line.strip()}", flush=True) # 等待进程结束 proc.wait() print(f"[初始.py 输出] 日志接收结束 (Exit Code: {proc.returncode})", flush=True) if proc.returncode == 0: print("[FINISH] 初始.py 执行完毕,正常结束", flush=True) else: print(f"[FINISH] 初始.py 异常结束,返回码: {proc.returncode}", flush=True) except Exception as e: print("[ERROR] 执行初始.py异常:", str(e), flush=True) finally: with GLOBAL_LOCK: IS_RUNNING_CHUSHI = False print("[UNLOCK] 已自动解锁,下次可重新触发", flush=True) def read_function(): os.makedirs(BASE_DIR, exist_ok=True) if not os.path.exists(LOG_FILE): with open(LOG_FILE, "w", encoding="utf-8") as f: f.write(time.strftime("%Y-%m-%d %H:%M:%S") + "\n") with open(LOG_FILE, "r", encoding="utf-8") as f: return f.read() def save_function(content): os.makedirs(BASE_DIR, exist_ok=True) with open(LOG_FILE, "w", encoding="utf-8") as f: f.write(str(content)) return "ok" def captcha_function(): try: now = time.time() aa = read_function().split("\n") if len(aa) > 0: try: ft = time.strptime(aa[0].strip(), "%Y-%m-%d %H:%M:%S") diff = abs(now - time.mktime(ft)) if diff > 120: time.sleep(1.3) aa = read_function().split("\n") except: pass if len(aa) < 2: return {"errorCode":"50","randstr":"","ticket":"","errMessage":"无结果","sess":""} res_line = aa[1] aa.pop(1) s = "" for i in range(len(aa)): if i == len(aa)-1: s += aa[i] else: s += aa[i] + "\n" save_function(s) return json.loads(res_line.replace("'", "\"")) except Exception as e: return {"errorCode":"50","randstr":"","ticket":"","errMessage":str(e),"sess":""} @app.route("/go", methods=["GET","POST"]) def api_go(): print("[REQUEST] 收到 /go?665 打码请求", flush=True) has665 = "665" in request.url if not has665: print("[DENY] 缺少665参数,拒绝执行", flush=True) return jsonify({ "status": "-1", "message": "参数错误,未启动打码程序", "enableExecuted": has665 }) res = captcha_function() if res.get("errorCode") != "50": print("[SUCCESS] 直接返回已有打码结果", flush=True) res["enableExecuted"] = has665 return jsonify(res) # 无结果才允许开线程 with GLOBAL_LOCK: if not IS_RUNNING_CHUSHI: threading.Thread(target=run_chushi_py).start() return jsonify({ "errorCode":"50", "randstr":"", "ticket":"", "sess":"", "errMessage":"暂无结果,已后台执行初始.py,请稍后重试", "enableExecuted": has665 }) @app.route("/") def index(): return jsonify({"tip":"访问 /go?665"}) # 应急手动解锁接口 @app.route("/unlock") def unlock(): global IS_RUNNING_CHUSHI with GLOBAL_LOCK: IS_RUNNING_CHUSHI = False print("[MANUAL] 管理员手动解锁成功", flush=True) return "手动解锁成功!" if __name__ == "__main__": # 启动强制清零锁 IS_RUNNING_CHUSHI = False print("[SERVICE] Flask打码服务启动,锁状态已初始化", flush=True) app.run(host="0.0.0.0", port=7860, debug=False)