使用 mitmproxy + python 做拦截代理

参考资料:

https://blog.wolfogre.com/posts/usage-of-mitmproxy/

https://ptorch.com/docs/10/mitmproxy_introduction

Step1:安装mitmproxy

windows安装:使用管理员权限打开cmd:pip3 install mitmproxy

使用mitmpdump --version查看版本,出现如下字样,则安装成功

C:\Users\wu>mitmproxy --version
Mitmproxy: 10.1.0
Python:    3.11.5
OpenSSL:   OpenSSL 3.1.3 19 Sep 2023
Platform:  Windows-10-10.0.19045-SP0

Step2:配置代理服务器

安装完成后,需要在电脑端的设置->网络->代理中开启手动代理,并输入相应的host和port

Step3:浏览器端安装代理管理插件

以chrome为例,使用SwitchOmega扩展插件配置代理:

SwitchyOmega 安装路径:https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif/related
SwitchyOmega安装及使用教程:https://blog.csdn.net/qq_45677671/article/details/127630795

Step4:配置浏览器端代理

Step5:运行mitmproxy

通过命令行的方式运行,在终端输入命令: mitmproxy -p 代理的端口(默认端口是8080)

Step6: 在网页访问链接:http://mitm.it/

 如果显示以下文字,则代理配置的不对,流量不走 mitmproxy

If you can see this, traffic is not passing through mitmproxy.

如果配置正确,打开 http://mitm.it 会显示如下界面:

Step7:下载安装证书

 点击上图的红框,安装windows下的证书

Step8:脚本编写参考博客
https://blog.csdn.net/m0_37641835/article/details/127853746

示例:

# -*- coding: utf-8 -*-
import mitmproxy.http
import os
import subprocess
from mitmproxy import ctx

file_path = os.path.abspath(__file__)

class Demo:
    def request(self, flow: mitmproxy.http.HTTPFlow):
        """Do something"""
        request = flow.request
        if 'https://www.baidu.com/' in request.url:
            keyword = request.query.get('wd')
            print(keyword)
            filter_words = ['迷药', '十八禁', "18"]
            if keyword == '雷锋':
                # 修改请求参数
                flow.request.query.set_all('wd', ['360搜索'])
            if keyword in filter_words:
                flow.response = mitmproxy.http.Response.make(
                    status_code=400,
                    content=''' <title>娘希匹!!!</title>
                                                <h1>警告!!!即将查水表</h1>
                                                <h2>望你善良,愿你向上</h2>
                                                <a>点击跳转:</a>
                                                <a href="https://space.bilibili.com/39880798" target="_blank">是小菜一碟吖的学习频道</a>
                                                ''',
                    # content="你可拉倒吧!!!查询的什么娘希匹玩意儿!!!"
                    headers={"Content-Type": "text/html"}
                )

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """Do something"""
        response = flow.response
        if flow.request.host == 'www.baidu.com':
            replace_words = ['你好', 'python', 'Python']
            text = response.get_text()
            text = list(map(lambda x: text.replace(x, '是小菜一碟吖'), replace_words))[0]
            flow.response.set_text(text=text)


addons = [
    Demo()
]
if __name__ == "__main__":
   # cmd = f"mitmweb -s {file_path}"
    os.system(f"mitmweb -s {file_path}")
View Code

 

posted @ 2023-09-26 14:43  enjoyzier  阅读(215)  评论(0编辑  收藏  举报