sdfgrtg commited on
Commit
0241ae6
·
verified ·
1 Parent(s): 1007e27

Create proxy.py

Browse files
Files changed (1) hide show
  1. proxy.py +39 -0
proxy.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import http.server
2
+ import urllib.request
3
+ import os
4
+
5
+ class HostFixProxy(http.server.BaseHTTPRequestHandler):
6
+ def log_message(self, format, *args): pass # 禁用无用日志
7
+
8
+ def handle_method(self, method):
9
+ # 1. 把来自外网的所有请求,完美打包转发给本地 9222 端口
10
+ url = f"http://127.0.0.1:9222{self.path}"
11
+ content_length = int(self.headers.get('Content-Length', 0))
12
+ data = self.rfile.read(content_length) if content_length > 0 else None
13
+
14
+ # 核心:重写 Host 请求头,强行伪装成本地 localhost
15
+ headers = {k: v for k, v in self.headers.items() if k.lower() != 'host'}
16
+ headers['Host'] = '127.0.0.1:9222'
17
+
18
+ try:
19
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
20
+ with urllib.request.urlopen(req, timeout=10) as res:
21
+ self.send_response(res.status)
22
+ for k, v in res.getheaders():
23
+ # 顺便把返回内容里的 ws://127.0.0.1 换成真实的 wss:// 外网地址
24
+ self.send_header(k, v)
25
+ self.end_headers()
26
+ self.wfile.write(res.read())
27
+ except Exception as e:
28
+ self.send_error(502, f"Proxy error: {e}")
29
+
30
+ def do_GET(self): self.handle_method("GET")
31
+ def do_POST(self): self.handle_method("POST")
32
+
33
+ if __name__ == "__main__":
34
+ # 后台启动 Chromium
35
+ os.system("chromium --headless --no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1 --remote-allow-origins=* &")
36
+ # 前台死守 7860
37
+ server = http.server.ThreadingHTTPServer(('0.0.0.0', 7860), HostFixProxy)
38
+ print("Proxy with Host-Fix is running on 7860...")
39
+ server.serve_forever()