Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo Proxy Web Server đơn giản Python

Mô tả

Proxy server trung gian giữa client và server đích. Nhận request từ client, forward đến server, trả response về client. Dùng để ẩn IP, cache, filter, bảo mật.

Lưu ý: Code gốc dùng module cũ (SimpleWebSocketServer, SimpleHTTPSServer, urllib Python 2 style). Dưới đây là phiên bản cập nhật Python 3.

Proxy HTTP đơn giản với http.server (Python 3)

from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.request
import urllib.error

class ProxyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        url = self.path[1:] if self.path.startswith('/') else self.path
        
        # Validate URL
        if not url.startswith(('https://', 'https://')):
            self.send_error(400, "Invalid URL")
            return
        
        try:
            # Forward request
            req = urllib.request.Request(url, headers={'User-Agent': 'Python-Proxy/1.0'})
            with urllib.request.urlopen(req, timeout=10) as response:
                self.send_response(response.status)
                # Copy headers
                for header, value in response.headers.items():
                    if header.lower() not in ('transfer-encoding', 'content-encoding'):
                        self.send_header(header, value)
                self.end_headers()
                # Stream response body
                self.copyfile(response, self.wfile)
        except urllib.error.HTTPError as e:
            self.send_error(e.code, str(e))
        except Exception as e:
            self.send_error(500, f"Proxy error: {e}")

    def log_message(self, format, *args):
        # Tắt log mặc định hoặc customize
        print(f"{self.client_address[0]} - {format % args}")

if __name__ == '__main__':
    PORT = 9012
    server = HTTPServer(('localhost', PORT), ProxyHandler)
    print(f"Proxy Server running on https://localhost:{PORT}")
    print("Usage: curl -x https://localhost:9012 https://example.com")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nShutting down...")
        server.shutdown()

Test Proxy

# Terminal 1: Chạy server
python proxy_server.py

# Terminal 2: Test với curl
curl -x https://localhost:9012 https://httpbin.org/get
curl -x https://localhost:9012 https://www.google.com

Proxy nâng cao với mitmproxy (Khuyên dùng production)

# Cài đặt: pip install mitmproxy
# Chạy: mitmproxy -p 8080
# Hoặc dùng trong code:
from mitmproxy import http, ctx

def request(flow: http.HTTPFlow):
    # Intercept và modify request
    flow.request.headers["X-Proxy"] = "Python-MitmProxy"
    
def response(flow: http.HTTPFlow):
    # Intercept response
    if "json" in flow.response.headers.get("content-type", ""):
        flow.response.text = flow.response.text.replace("old", "new")

So sánh

LoạiĐộ phức tạpTính năngPhù hợp
http.server customThấpBasic GET/POSTHọc tập, test đơn giản
mitmproxyTrung bìnhHTTPS intercept, modify, replay, scriptDebug, test, security research
squid/nginxCấu hìnhCache, ACL, load balancing, productionProduction proxy server

Cảnh báo: Proxy có thể xem được toàn bộ traffic HTTP (kể cả password nếu không HTTPS). Chỉ dùng trong môi trường tin cậy.