如何以编程方式关闭dumpmaster(mitmproxy)?

2024-04-16 20:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用mitmproxy拦截来自移动设备的一些请求/响应。我有一个代码块来启动它,如下所示:

import asyncio
from mitmproxy import proxy, options, ctx
from mitmproxy.tools.dump import DumpMaster
from mitmproxy import http


class AdjustBody:
    def response(self, flow: http.HTTPFlow) -> None:
        if "google" in flow.request.url:
            print("Before intercept: %s" % flow.response.text)
            flow.response.content = bytes("This is replacement response", "UTF-8")
            print("After intercept: %s" % flow.response.text)


def start():
    add_on = AdjustBody()

    opts = options.Options(listen_host='192.168.1.224', listen_port=8888, confdir="/Users/hienphan/.mitmproxy")
    proxy_conf = proxy.config.ProxyConfig(opts)

    dump_master = DumpMaster(opts)
    dump_master.server = proxy.server.ProxyServer(proxy_conf)
    dump_master.addons.add(add_on)

    try:
        asyncio.ensure_future(stop())
        dump_master.run()
    except KeyboardInterrupt:
        dump_master.shutdown()


async def stop():
    # Sleep 10s to do intercept
    await asyncio.sleep(10)
    ctx.master.shutdown()

start()

我可以正确地启动它,但它是一个run\u forever()事件循环。那我就不知道怎么用程序阻止它了。我在这里尝试的只是在关机前睡10秒钟做我想做的事。有没有办法在关闭代理之前等待我的拦截完成?你知道吗


Tags: fromimportmasteraddasyncioresponsedefflow