Code Snippets

Useful Python scripts for mitmproxy. Copy and paste directly into your project.

Log Request Headers

Simple script to print all request headers to the console.

Utility
from mitmproxy import http

def request(flow: http.HTTPFlow):
    print(f"Request headers for {flow.request.url}:")
    for k, v in flow.request.headers.items():
        print(f"{k}: {v}")

Modify Response Body

Replace text in response body.

Body
from mitmproxy import http

def response(flow: http.HTTPFlow):
    if flow.response.content:
        flow.response.content = flow.response.content.replace(
            b"Hello", b"Bye"
        )

Add Custom Header

Inject a custom header into every request.

Headers
from mitmproxy import http

def request(flow: http.HTTPFlow):
    flow.request.headers["X-Custom-Header"] = "ProxyPilot"

Delay Requests

Add a 2-second delay to all requests matching a specific domain.

Flow Control
from mitmproxy import http
import time

def request(flow: http.HTTPFlow):
    if "example.com" in flow.request.pretty_host:
        time.sleep(2)

Redirect Request

Redirect traffic from one domain to another.

Flow Control
from mitmproxy import http

def request(flow: http.HTTPFlow):
    if flow.request.pretty_host == "example.com":
        flow.request.host = "localhost"
        flow.request.port = 8080
        flow.request.scheme = "http"

Filter by Content-Type

Only process responses with specific content types (e.g., JSON).

Utility
from mitmproxy import http

def response(flow: http.HTTPFlow):
    if "application/json" in flow.response.headers.get("content-type", ""):
        print(f"JSON response received from {flow.request.url}")