我正在使用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秒来做我想做的事情。有没有办法在关闭代理之前等待我的拦截完成?
发布于 2020-08-14 13:02:19
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发布于 2020-08-27 19:36:28
前段时间,我开发了一个在后台运行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()https://stackoverflow.com/questions/57178896
复制相似问题