Useful Python scripts for mitmproxy. Copy and paste directly into your project.
Simple script to print all request headers to the console.
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}")
Replace text in response 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"
)
Inject a custom header into every request.
from mitmproxy import http
def request(flow: http.HTTPFlow):
flow.request.headers["X-Custom-Header"] = "ProxyPilot"
Add a 2-second delay to all requests matching a specific domain.
from mitmproxy import http
import time
def request(flow: http.HTTPFlow):
if "example.com" in flow.request.pretty_host:
time.sleep(2)
Redirect traffic from one domain to another.
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"
Only process responses with specific content types (e.g., JSON).
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}")