import http.server import socketserver import urllib.request from urllib.parse import urlparse PORT = 8000 class SimpleProxyHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): # ターゲットURLを解析 parsed_url = urlparse(self.path) if parsed_url.scheme not in ('http', 'https'): self.send_error(400, "Bad Request: Scheme must be http or https") return # ターゲットサーバーへリクエストを転送 try: # 元のリクエストヘッダーの一部を引き継ぐ req = urllib.request.Request(self.path, headers={ 'User-Agent': self.headers['User-Agent'] }) with urllib.request.urlopen(req) as remote_response: # クライアントに応答を返す self.send_response(remote_response.status) for header, value in remote_response.headers.items(): self.send_header(header, value) self.end_headers() self.copyfile(remote_response, self.wfile) except Exception as e: self.send_error(500, f"Proxy Error: {e}") # プロキシサーバーを起動 with socketserver.TCPServer(("", PORT), SimpleProxyHandler) as httpd: print(f"Serving at port {PORT}...") print(f"Use this proxy in your browser/client with address 127.0.0.1:{PORT}") httpd.serve_forever()