在python脚本中使用mitmproxy

时间:2018-08-17 10:51:39

标签: python mitmproxy

我是mitmproxy的新手。但是我不知道如何在python脚本中使用它。

我想将mitmproxy像库一样放入我的python脚本中,并且还具体指定端口或主机之类的所有内容,并在python脚本中使用Request或Response进行一些修改。 所以当我这样启动脚本

python sample.py

一切都会自动运行,而无需像这样从命令行运行mitmproxy

mitmproxy -s sample.py

感谢阅读。

2 个答案:

答案 0 :(得分:2)

以编程方式在后台启动mitmproxy ,以将其集成到现有应用中:

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 might be started too.
    time.sleep(20)
    print('going to shutdown mitmproxy')
    m.shutdown()

来自my gist

答案 1 :(得分:1)

您可以使用类似这样的东西。这段代码来自发布在here

的mithproxy github上的问题
from mitmproxy import proxy, options
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.addons import core


class AddHeader:
    def __init__(self):
        self.num = 0

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


addons = [
    AddHeader()
]

opts = options.Options(listen_host='127.0.0.1', listen_port=8080)
pconf = proxy.config.ProxyConfig(opts)

m = DumpMaster(None)
m.server = proxy.server.ProxyServer(pconf)
# print(m.addons)
m.addons.add(addons)
print(m.addons)
# m.addons.add(core.Core())

try:
    m.run()
except KeyboardInterrupt:
    m.shutdown()