# -*- coding: utf-8 -*- r'''清掉 _build/ 里剩下的 5 处明文管理密码。 形状: _build/check_web.sh:29 -d 'username=xmz7891&password=<旧>' "$BASE/admin/login" _build/verify_site_admin.sh:38 同上 _build/split_site_admin2.py:10 注释里 _build/split_site_admin2.py:22 ADMIN_PASS = "<旧>" _build/test_response_headers.py:28 PASS = "<旧>" 改法: * shell 脚本改成从环境变量读:${RELAY_ADMIN_PASSWORD:?请先设置} * Python 改成 os.environ.get("RELAY_ADMIN_PASSWORD") * 注释里把密码删掉,改成说明怎么取 ''' from __future__ import annotations import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent OLD = "REVA" + "edu120830" passed = 0 failed = 0 def report(name, ok, detail=""): global passed, failed if ok: passed += 1 print(" ✓ " + name) else: failed += 1 print(" ✗ " + name + ((" —— " + str(detail)) if detail else "")) def main() -> int: # ---- shell 脚本:改成读环境变量 ---- for name in ("check_web.sh", "verify_site_admin.sh"): p = ROOT / "_build" / name if not p.is_file(): report(name, False, "不存在") continue t = p.read_text(encoding="utf-8") if OLD not in t: report(name, True, "已干净,跳过") continue before = t t = re.sub( r"-d\s+'username=[^']*&password=[^']*'", '-d "username=xmz7891&password=$RELAY_ADMIN_PASSWORD"', t) if t == before: report(name, False, "替换没生效") continue if OLD in t: report(name, False, "还有残留") continue # 在文件顶部加一句检查,免得忘设环境变量时报错莫名其妙 lines = t.splitlines() insert_at = 0 for i, line in enumerate(lines[:12]): if line.startswith("#!"): insert_at = i + 1 break lines.insert(insert_at, "") lines.insert(insert_at + 1, '# ⚠ 管理密码不再写在这里,从环境变量取:') lines.insert(insert_at + 2, '# export RELAY_ADMIN_PASSWORD=...') lines.insert(insert_at + 3, ': "${RELAY_ADMIN_PASSWORD:?请先 export RELAY_ADMIN_PASSWORD}"') p.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") report(name, True, "改成读环境变量") # ---- Python:改成 os.environ ---- for name in ("split_site_admin2.py", "test_response_headers.py"): p = ROOT / "_build" / name if not p.is_file(): report(name, False, "不存在") continue t = p.read_text(encoding="utf-8") if OLD not in t: report(name, True, "已干净,跳过") continue before = t # ADMIN_PASS = "..." / PASS = "..." t = re.sub(r'(\w*PASS\w*)\s*=\s*"%s"' % re.escape(OLD), r'\1 = (os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()', t) # 注释里的 t = t.replace(OLD, "(从 RELAY_ADMIN_PASSWORD 环境变量读)") t = t.replace('"%s"' % OLD, '""') t = t.replace(OLD, "") if OLD in t: report(name, False, "还有残留") continue if t == before: report(name, False, "替换没生效") continue # 确保有 import os if "import os" not in t: m = re.search(r"^(import |from )", t, re.M) if m: t = t[:m.start()] + "import os\n" + t[m.start():] else: t = "import os\n" + t p.write_text(t, encoding="utf-8", newline="\n") report(name, True, "改成读环境变量") print() print(" 改了 %d 个,失败 %d 个" % (passed, failed)) return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())