python接口自动化12-流量回放神器:mitmproxy(下)

一、mitmproxy做扩展

比如接口用例信息收集,回放对比,安全测试都可以那么便可以通过:mitmdump -s xx.py

扩展可查阅中文文档:https://ptorch.com/docs/10/addons-overview

1、有需求将某些请求域名包含的,写入文档方便回放,或者入库等。

复制代码
import time
import json


def dumps(txt, beaut=0):
    """ json序列化:dict -> json """
    try:
        if beaut:
            txt = json.dumps(txt, sort_keys=True, indent=4, ensure_ascii=False)
        else:
            txt = json.dumps(txt, ensure_ascii=False)
    except:
        txt = txt
    return txt


def loads(txt):
    """ json反序列化:json -> dict """
    try:
        txt = json.loads(txt, encoding='UTF-8')
    except:
        txt = txt
    return txt


def response(flow):
    # 加上过滤条件
    if flow.request.host in ['192.168.1.1']:
        request_data, headers = {}, {}
        # 请求信息组装
        request_data['method'] = flow.request.method
        request_data['url'] = flow.request.pretty_url
        # headers
        for key, value in flow.request.headers.items():
            headers[key] = value
        request_data['headers'] = headers
        # body
        is_body = loads(flow.request.content.decode('utf-8'))
        if is_body:
            if isinstance(is_body, dict):
                body = {'json': is_body}
            else:
                body = {'data': is_body}
            request_data.update(body)
        request_data['response'] = loads(flow.response.content.decode('utf-8'))
        # 写入文件
        file = f'mitm-{time.strftime("%Y-%m-%d", time.localtime())}.txt'
        with open(file, 'a+', encoding='utf-8')as f:
            f.write(dumps(request_data) + '\n')
复制代码

2、指定的域名将请求与响应信息抓取下来保存为文件,再做进一步处理或API测试,美哉!

平时功能测试时开好代理,将API请求信息抓取到。

流量回放替代人工写了一部分用例,或者做冒烟测试时可以直接使用只请求GET类型,这样不用担心参数化关联或参数无效情况。

 

结束

 

posted @   广深-小龙  阅读(376)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示