# -*- coding: utf-8 -*- """修 _PRIVATE_HOST 正则:.local(mDNS 名字)判断失败。 问题:正则第一条分支以 `^` 开头,我用的是 re.match(从位置 0 起匹配), 所以 `\.local$` 这条分支对 `lanremote.local:8080` 永远匹配不上 (`.local` 不在位置 0)。 改成结构清晰的一条:主机名整体匹配,各分支用 | 分开, 末尾统一接可选的端口。 """ from __future__ import annotations import sys from pathlib import Path RELAY = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote\windows" r"\lanremote\relay.py") OLD_START = '''# 私有网段 + 回环,这些肯定是局域网,用明文 HTTP _PRIVATE_HOST = re.compile(''' # 找到整块(到 __init__ 之前的空行) OLD_END = '''def _guess_scheme(address: str) -> str:''' NEW_BLOCK = '''# 私有网段 + 回环 + mDNS 名字 —— 这些肯定是局域网,用明文 HTTP _PRIVATE_HOST = re.compile( r"^(?:" r"localhost" r"|127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" r"|10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" r"|192\\.168\\.\\d{1,3}\\.\\d{1,3}" r"|172\\.(?:1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}" r"|\\d{1,3}(?:\\.\\d{1,3}){3}" # 任意纯 IP(含公网) r"|[^./:]+\\.local" # mDNS 名字,如 lanremote.local r")" r"(?::\\d{1,5})?$", re.IGNORECASE) def _guess_scheme(address: str) -> str: """用户没写 http/https 时,猜一个。 IP 地址 / localhost / *.local -> http:// 局域网里的中转服务是明文 HTTP。猜成 https 会永远连不上, 而且报的是 SSL 错误,很容易把人带去查证书(查半天查不出)。 域名 -> https:// 走公网必须加密(Cloudflare 隧道本来就是 https)。 """ host = address.split("/", 1)[0] return "http://" if _PRIVATE_HOST.match(host) else "https://" ''' def main() -> int: text = RELAY.read_text(encoding="utf-8") start = text.find(OLD_START) if start < 0: print(" [失败] 找不到 _PRIVATE_HOST") return 1 # 从 start 找到下一个 def _guess_scheme 之前 end = text.find(OLD_END, start) if end < 0: print(" [失败] 找不到 _guess_scheme") return 1 text = text[:start] + NEW_BLOCK + text[end + len(OLD_END):] RELAY.write_text(text, encoding="utf-8", newline="\n") import ast try: ast.parse(text) print(" 语法 OK") except SyntaxError as exc: print(f" 语法错误: {exc}") return 1 print(" _PRIVATE_HOST 已重写") return 0 if __name__ == "__main__": sys.exit(main())