mitmproxy addons
概述
在之前的文章简单介绍了mitmproxy的基本用法。近期在工作中刚好用到,需要在自动化测试过程中对特定的请求做处理,因此再重新温习下
proxy封装
import os
import subprocess
class Proxy:
def __init__(self, addons_path=None, port="8888", filter_regex=None):
self.addons_path = addons_path
self.port = port
self.filter_regex = filter_regex
def start_mitmproxy(self):
script = ['-s', self.addons_path] if self.addons_path else []
filter_domain = ['~d', self.filter_regex] if self.filter_regex else []
args = ["mitmdump", "-p", self.port] + script + filter_domain
self.mitmproxy_subprocess = subprocess.Popen(args, stdout=subprocess.PIPE,
encoding='utf-8')
return self.mitmproxy_subprocess
def shutdown_mitmproxy(self):
if not self.mitmproxy_subprocess.poll():
self.mitmproxy_subprocess.terminate()
def __enter__(self):
self.start_mitmproxy()
def __exit__(self, exc_type, exc_val, exc_tb):
self.shutdown_mitmproxy()
在项目中就可以直接使用上下文管理with proxy
来管理mitmproxy的启动和关闭了
过滤器
如上脚本中使用了~d regex
来过滤特定的domain的请求,更多fliter表达式可参看mitmproxy官方Filter expressions
addons
- 添加header
'''adds a header to every request.'''
def request(flow):
flow.request.headers["myheader"] = "value"
- mock
"""Send a reply from the proxy without sending any data to the remote server."""
from mitmproxy import http
def request(flow: http.HTTPFlow) -> None:
if flow.request.pretty_url == "http://example.com/path":
flow.response = http.HTTPResponse.make(
200, # (optional) status code
b"Hello World", # (optional) content
{"Content-Type": "text/html"} # (optional) headers
)
不只是request 事件(event),更多关于http协议支持的event可参看HTTP Events
- 更多addons示例可参看addons examples