如何以编程方式关闭转储程序(代理)



我正在使用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_forever(( 事件循环。然后我不知道如何以编程方式停止它。我在这里尝试的只是在关闭它之前睡 10 秒做我想做的事情。在关闭代理之前,有什么方法可以等待我的拦截完成?

你可以试试这个

import asyncio
import os
import signal
from mitmproxy import proxy, options
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.http import HTTPFlow

class AddHeader:
    def __init__(self):
        self.num = 0
    def response(self, flow: HTTPFlow):
        self.num = self.num + 1
        flow.response.headers["count"] = str(self.num)

addons = [
    AddHeader()
]
opts = options.Options(listen_host='0.0.0.0', listen_port=8080)
pconf = proxy.config.ProxyConfig(opts)
m = DumpMaster(opts)
m.server = proxy.server.ProxyServer(pconf)
m.addons.add(*addons)
try:
    loop = asyncio.get_event_loop()
    try:
        loop.add_signal_handler(signal.SIGINT, getattr(m, "prompt_for_exit", m.shutdown))
        loop.add_signal_handler(signal.SIGTERM, m.shutdown)
    except NotImplementedError:
        # Not supported on Windows
        pass
    # Make sure that we catch KeyboardInterrupts on Windows.
    # https://stackoverflow.com/a/36925722/934719
    if os.name == "nt":
        async def wakeup():
            while True:
                await asyncio.sleep(0.2)
        asyncio.ensure_future(wakeup())
    m.run()
except (KeyboardInterrupt, RuntimeError):
    pass

前段时间我开发了一个在后台运行 mitmproxy 的脚本,同时处理其他一些东西。我尝试控制主线程,但找不到易于理解的可行解决方案。

我个人的偏好是使用 Python 的线程模块启动一个侧线程,在 10 秒后关闭转储主服务器。

例:

import threading
import sleep
...
# Initialise dump_master somewhere here
...
def countdown(dump_master):
    time.sleep(10)
    dump_master.shutdown()
# Start countdown function with dump_master as argument in new thread
timer = threading.Thread(
    target=countdown, args=[dump_master], daemon=True)
timer.start()
# Start dumpmaster
dump_master.run()

最新更新