编写HTTP/1.1和HTTP/2.0脚本

有时,我们希望编写一个快速的脚本而不会遇到创建类的麻烦。addons机制具有一种速记方式,可以将模块作为一个整体视为一个addon对象。这使我们可以将事件处理程序函数放在模块作用域中。例如,下面是一个完整的脚本,它向每个请求添加标头。

def request(flow):
    flow.request.headers["myheader"] = "value"

这是另一个截取对特定URL的请求并发送任意响应的示例:

"""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
        )

可以在此处找到有关HTTP协议的所有事件。

对于与HTTP相关的对象,请查看[http] []模块或[Request] []和[Response] []类,以获取在编写脚本时可以使用的其他属性。

脚本化WebSocket

在客户端和服务器同意将连接升级到WebSocket之前,WebSocket协议最初看起来像是常规HTTP请求。初始HTTP握手的所有脚本事件以及专用的WebSocket事件都可以在此处找到

"""Process individual messages from a WebSocket connection."""
import re
from mitmproxy import ctx

def websocket_message(flow):
    # get the latest message
    message = flow.messages[-1]

    # was the message sent from the client or server?
    if message.from_client:
        ctx.log.info("Client sent a message: {}".format(message.content))
    else:
        ctx.log.info("Server sent a message: {}".format(message.content))

    # manipulate the message content
    message.content = re.sub(r'^Hello', 'HAPPY', message.content)

    if 'FOOBAR' in message.content:
        # kill the message and not send it to the other endpoint
        message.kill()

对于与WebSocket相关的对象,请查看websocket模块以查找在编写脚本时可以使用的所有属性。

编写TCP脚本

可以在此处找到有关TCP协议的所有事件。

"""
Process individual messages from a TCP connection.

This script replaces full occurences of "foo" with "bar" and prints various details for each message.
Please note that TCP is stream-based and *not* message-based. mitmproxy splits stream contents into "messages"
as they are received by socket.recv(). This is pretty arbitrary and should not be relied on.
However, it is sometimes good enough as a quick hack.

Example Invocation:

    mitmdump --rawtcp --tcp-hosts ".*" -s examples/tcp-simple.py
"""
from mitmproxy.utils import strutils
from mitmproxy import ctx
from mitmproxy import tcp

def tcp_message(flow: tcp.TCPFlow):
    message = flow.messages[-1]
    message.content = message.content.replace(b"foo", b"bar")

    ctx.log.info(
        f"tcp_message[from_client={message.from_client}), content={strutils.bytes_to_escaped_str(message.content)}]"
    )

对于与WebSocket相关的对象,请查看tcp模块以查找在编写脚本时可以使用的所有属性。