Using mitmproxy inside python script

j3ssie picture j3ssie · Aug 17, 2018 · Viewed 8.7k times · Source

I new in mitmproxy. But I can't figure out how to used that in python script.

I want to put mitmproxy into my python script just like a library and also specific everything like port or host and do some modify with Request or Response in my python script. So when I start my script like this

python sample.py

Everything will run automatic without run mitmproxy from commandline like this

mitmproxy -s sample.py

Thanks for reading.

Answer

securisec picture securisec · Sep 1, 2018

You can use something like this. This code was taken from an issue posted on the mithproxy github found here

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