首页 > 解决方案 > 有没有办法在后台以编程方式启动 mitmproxy v.7.0.2?

问题描述

有没有办法在后台以编程方式启动 mitmproxy v.7.0.2?ProxyConfig 和 ProxyServer 自 7.0.0 版本以来已被删除,下面的代码不起作用。

from mitmproxy.options import Options
from mitmproxy.proxy.config import ProxyConfig
from mitmproxy.proxy.server import ProxyServer
from mitmproxy.tools.dump import DumpMaster

import threading
import asyncio
import time

class Addon(object):
    def __init__(self):
        self.num = 1

    def request(self, flow):
        flow.request.headers["count"] = str(self.num)

    def response(self, flow):
        self.num = self.num + 1
        flow.response.headers["count"] = str(self.num)
        print(self.num)


# see source mitmproxy/master.py for details
def loop_in_thread(loop, m):
    asyncio.set_event_loop(loop)  # This is the key.
    m.run_loop(loop.run_forever)


if __name__ == "__main__":
    options = Options(listen_host='0.0.0.0', listen_port=8080, http2=True)
    m = DumpMaster(options, with_termlog=False, with_dumper=False)
    config = ProxyConfig(options)
    m.server = ProxyServer(config)
    m.addons.add(Addon())

    # run mitmproxy in backgroud, especially integrated with other server
    loop = asyncio.get_event_loop()
    t = threading.Thread( target=loop_in_thread, args=(loop,m) )
    t.start()

    # Other servers, such as a web server, might be started then.
    time.sleep(20)
    print('going to shutdown mitmproxy')
    m.shutdown()

来自 BigSully 的要点

标签: mitmproxy

解决方案


你可以把你的Addon类放进去your_script.py然后运行mitmdump -s your_script.py。mitmdump 没有控制台界面,可以在后台运行。

我们(mitmproxy 开发人员)正式不再支持从 Python 手动实例化,因为这给我们带来了大量的支持负担。如果你有一些 Python 经验,你可能会找到自己的方法。

如果我的插件有额外的依赖项怎么办?

方法 1: pip install mitmproxy仍然得到完美支持,并为您提供与独立二进制文件相同的功能。额外提示:您可以在 virtualenv 中运行venv/bin/mitmproxyvenv/Scripts/mitmproxy.exe调用 mitmproxy,而无需激活您的 virtualenv。

方法 2:您可以安装 mitmproxy,pipx然后运行pipx inject mitmproxy <your dependency name>​​. 有关详细信息,请参阅https://docs.mitmproxy.org/stable/overview-installation/#installation-from-the-python-package-index-pypi

如何调试 mitmproxy 本身?

如果您从命令行调试(无论是打印语句还是 pdb),最简单的方法是运行mitmdump而不是运行mitmproxy,它提供了相同的功能,但没有控制台界面。或者,您可以使用 PyCharm 的远程调试功能,该功能在控制台界面处于活动状态时也可以使用 ( https://github.com/mitmproxy/mitmproxy/blob/main/examples/contrib/remote-debug.py )。


推荐阅读