- Flask 控制台:Cliproxy 巡检、批量补号、流水线、运行日志 - codex_stats_oauth_dir 支持统计 Cliproxy auth 目录 - 忽略 accounts/oauth、.venv、本地 DB/日志与 new.py Made-with: Cursor
257 lines
8.4 KiB
Python
257 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""OpenAI 协议注册机 - 直接运行 python run.py 即可
|
|
|
|
修改下面的配置即可控制行为:
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import sys
|
|
import threading
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from datetime import datetime, timezone, timedelta
|
|
|
|
# ╔══════════════════════════════════════════════════════════╗
|
|
# ║ 配 置 区 域 ║
|
|
# ║ 修改以下变量即可,直接 python run.py 运行 ║
|
|
# ╚══════════════════════════════════════════════════════════╝
|
|
|
|
THREADS = 1 # 并行线程数 (1 = 单线程顺序执行)
|
|
COUNT = 50 # 注册账号数量
|
|
SKIP_OAUTH = False # True = 只注册不做 OAuth 获取 token
|
|
PROXY = "http://127.0.0.1:7897" # 代理地址
|
|
|
|
# ══════════════════════════════════════════════════════════
|
|
|
|
# 确保当前目录在 sys.path 中
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
from register import AccountRegister, RegisterConfig, RegisterResult
|
|
from oauth_login import OAuthLogin, PasswordMismatchError, BannedError
|
|
from oauth_client import generate_pkce, build_authorize_url, exchange_code
|
|
|
|
ACCOUNTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "accounts")
|
|
|
|
_lock = threading.Lock()
|
|
_counter = {"success": 0, "failed": 0}
|
|
|
|
# 供控制台批量任务写入 cpa_id / cpa_code(线程局部,避免并行任务互相污染)
|
|
_register_ctx = threading.local()
|
|
|
|
|
|
def set_register_context(*, cpa_id: int | None = None, cpa_code: str | None = None) -> None:
|
|
_register_ctx.cpa_id = cpa_id
|
|
_register_ctx.cpa_code = cpa_code
|
|
|
|
|
|
def clear_register_context() -> None:
|
|
_register_ctx.cpa_id = None
|
|
_register_ctx.cpa_code = None
|
|
|
|
|
|
def _merge_register_context(record: dict) -> None:
|
|
cid = getattr(_register_ctx, "cpa_id", None)
|
|
code = getattr(_register_ctx, "cpa_code", None)
|
|
if cid is not None:
|
|
record["cpa_id"] = cid
|
|
if code:
|
|
record["cpa_code"] = code
|
|
|
|
|
|
def do_register(config: RegisterConfig) -> RegisterResult:
|
|
reg = AccountRegister(config=config)
|
|
return reg.register_one()
|
|
|
|
|
|
def do_oauth(email: str, password: str, proxy: str) -> dict:
|
|
pkce = generate_pkce()
|
|
state = "bot_" + datetime.now().strftime("%Y%m%d%H%M%S")
|
|
auth_url = build_authorize_url(pkce, state=state)
|
|
|
|
login = OAuthLogin(proxy=proxy)
|
|
code = login.authorize(
|
|
auth_url=auth_url,
|
|
state=state,
|
|
email=email,
|
|
password=password,
|
|
use_email_otp=True,
|
|
)
|
|
|
|
tokens = exchange_code(code, pkce["code_verifier"], proxy=proxy)
|
|
return tokens
|
|
|
|
|
|
def _decode_jwt_payload(token: str) -> dict:
|
|
"""解码 JWT payload(不验证签名)"""
|
|
try:
|
|
parts = token.split(".")
|
|
if len(parts) < 2:
|
|
return {}
|
|
payload_b64 = parts[1]
|
|
padded = payload_b64 + "=" * (4 - len(payload_b64) % 4)
|
|
decoded = base64.urlsafe_b64decode(padded)
|
|
return json.loads(decoded.decode("utf-8"))
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def _email_to_filename(email: str | None) -> str:
|
|
"""将邮箱转为文件名: @ 和 . 替换为 _;空值回退 unknown"""
|
|
if not email:
|
|
return "unknown"
|
|
return str(email).replace("@", "_").replace(".", "_")
|
|
|
|
|
|
def save_account(record: dict, *, is_failed: bool = False):
|
|
"""按状态保存到不同子文件夹:
|
|
- accounts/oauth/ 注册+OAuth 都成功
|
|
- accounts/unoauth/ 注册成功但未做/跳过 OAuth
|
|
- accounts/failed/ 注册失败或 OAuth 失败
|
|
"""
|
|
if is_failed:
|
|
subdir = "failed"
|
|
elif record.get("type") == "codex":
|
|
subdir = "oauth"
|
|
else:
|
|
subdir = "unoauth"
|
|
|
|
target_dir = os.path.join(ACCOUNTS_DIR, subdir)
|
|
os.makedirs(target_dir, exist_ok=True)
|
|
|
|
_merge_register_context(record)
|
|
email = record.get("email", "unknown")
|
|
filename = _email_to_filename(email)
|
|
filepath = os.path.join(target_dir, f"{filename}.json")
|
|
with open(filepath, "w", encoding="utf-8") as f:
|
|
json.dump(record, f, ensure_ascii=False, indent=2)
|
|
print(f"[save] {filepath}")
|
|
|
|
|
|
def _build_oauth_record(email: str, tokens: dict) -> dict:
|
|
"""从 OAuth token 响应构建目标格式的 record"""
|
|
access_token = tokens.get("access_token", "")
|
|
refresh_token = tokens.get("refresh_token", "")
|
|
id_token = tokens.get("id_token", "")
|
|
|
|
# 从 access_token 解析 account_id 和 expired
|
|
jwt_payload = _decode_jwt_payload(access_token)
|
|
auth_info = jwt_payload.get("https://api.openai.com/auth", {})
|
|
account_id = auth_info.get("chatgpt_account_id", "")
|
|
|
|
# exp → ISO 8601 带时区
|
|
exp = jwt_payload.get("exp")
|
|
if exp:
|
|
expired_dt = datetime.fromtimestamp(exp, tz=timezone(timedelta(hours=8)))
|
|
expired = expired_dt.isoformat()
|
|
else:
|
|
expired = ""
|
|
|
|
now_dt = datetime.now(tz=timezone(timedelta(hours=8)))
|
|
|
|
return {
|
|
"access_token": access_token,
|
|
"account_id": account_id,
|
|
"disabled": False,
|
|
"email": email,
|
|
"expired": expired,
|
|
"id_token": id_token,
|
|
"last_refresh": now_dt.isoformat(),
|
|
"refresh_token": refresh_token,
|
|
"type": "codex",
|
|
}
|
|
|
|
|
|
def _do_one(index: int, config: RegisterConfig, proxy: str, skip_oauth: bool) -> dict:
|
|
result = do_register(config)
|
|
|
|
if not result.success:
|
|
record = {
|
|
"email": result.email,
|
|
"password": result.password,
|
|
"register_error": result.error or "unknown",
|
|
}
|
|
save_account(record, is_failed=True)
|
|
with _lock:
|
|
_counter["failed"] += 1
|
|
return record
|
|
|
|
if skip_oauth:
|
|
record = {"email": result.email, "password": result.password}
|
|
save_account(record)
|
|
with _lock:
|
|
_counter["success"] += 1
|
|
return record
|
|
|
|
try:
|
|
tokens = do_oauth(result.email, result.password, proxy)
|
|
record = _build_oauth_record(result.email, tokens)
|
|
record["password"] = result.password
|
|
save_account(record)
|
|
with _lock:
|
|
_counter["success"] += 1
|
|
except PasswordMismatchError as e:
|
|
record = {"email": result.email, "password": result.password, "oauth_error": f"password_mismatch: {e}"}
|
|
save_account(record, is_failed=True)
|
|
with _lock:
|
|
_counter["failed"] += 1
|
|
except BannedError as e:
|
|
record = {"email": result.email, "password": result.password, "oauth_error": f"banned: {e}"}
|
|
save_account(record, is_failed=True)
|
|
with _lock:
|
|
_counter["failed"] += 1
|
|
except Exception as e:
|
|
record = {"email": result.email, "password": result.password, "oauth_error": str(e)}
|
|
save_account(record, is_failed=True)
|
|
with _lock:
|
|
_counter["failed"] += 1
|
|
|
|
return record
|
|
|
|
|
|
def main():
|
|
count = COUNT
|
|
threads = max(1, min(THREADS, count))
|
|
proxy = PROXY
|
|
skip_oauth = SKIP_OAUTH
|
|
|
|
config = RegisterConfig(proxy=proxy)
|
|
|
|
_counter["success"] = 0
|
|
_counter["failed"] = 0
|
|
|
|
print(f"开始批量注册: {count} 个账号, {threads} 线程并行")
|
|
print(f"代理: {proxy}")
|
|
print(f"跳过 OAuth: {skip_oauth}")
|
|
print(f"{'='*60}")
|
|
|
|
import time as _time
|
|
start_time = _time.time()
|
|
|
|
if threads <= 1:
|
|
for i in range(count):
|
|
_do_one(i + 1, config, proxy, skip_oauth)
|
|
else:
|
|
with ThreadPoolExecutor(max_workers=threads) as executor:
|
|
futures = {
|
|
executor.submit(_do_one, i + 1, config, proxy, skip_oauth): i
|
|
for i in range(count)
|
|
}
|
|
for future in as_completed(futures):
|
|
try:
|
|
future.result()
|
|
except Exception as e:
|
|
print(f"[error] 线程异常: {e}")
|
|
|
|
elapsed = _time.time() - start_time
|
|
avg_time = elapsed / count if count > 0 else 0
|
|
|
|
print(f"\n{'='*60}")
|
|
print(f"完成: 成功 {_counter['success']}, 失败 {_counter['failed']}, 共 {count}")
|
|
print(f"总耗时: {elapsed:.1f}s | 平均速度: {avg_time:.1f}s/个")
|
|
print(f"账号文件保存在: {ACCOUNTS_DIR}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |