mitmproxy 单个链接配置不同的代理

By | October 11, 2022

本来目的是为了实现网址的图片访问不同的代理(本地代理)节约流量
可以实现针对性的给不同的URL配置不同代理

from mitmproxy import ctx, http
from mitmproxy.connection import Server
from mitmproxy.connection import ConnectionState
from mitmproxy.net.server_spec import ServerSpec

def requestheaders(flow: http.HTTPFlow) -> None:
    #判断后缀,这些使用本地代理,不使用上级代理,options里需要启用: --set connection_strategy=lazy --set upstream_cert=false
    current_url = flow.request.url
    suffix = current_url.split('.')[-1]
    proxy_address = flow.server_conn.via.address

    if  suffix in ['jpg','png','ico','woff2','woff','mp4']:      
        if proxy_address != ("127.0.0.1", 8282):
            if flow.server_conn.timestamp_start:
                flow.server_conn = Server(flow.server_conn.address)    
                flow.server_conn.state = ConnectionState.CLOSED
            flow.server_conn.via = ServerSpec("http", address=("127.0.0.1", 8282))
        else:
            return
    else:  #不清楚什么原因,有些URL也会使用本地代理,这种情况就把代理重新给配置为upstream_proxy
        if proxy_address == ("127.0.0.1", 8282):
            print(suffix,current_url)
            upstream_proxy = ctx.master.options.__getattr__('mode')
            http_proxy = upstream_proxy.split('//')[-1].split(':')
            print(http_proxy)
            flow.server_conn.via = ServerSpec("http", address=(http_proxy[0], http_proxy[1]))
        else:
            return

测试结果能实现图片等使用本地代理:

参考: https://blog.csdn.net/windywolf301/article/details/123533226
https://www.anycodings.com/1questions/1046480/how-to-make-a-network-request-inside-a-mitmproxy-addon

Leave a Reply