【问题标题】:Return custom response with mitmproxy使用 mitmproxy 返回自定义响应
【发布时间】:2019-06-09 05:40:14
【问题描述】:

我在使用 mitmproxy 时尝试返回自定义响应,代码如下

from libmproxy.models import HTTPResponse
from netlib.http import Headers

def request(context, flow):
    if flow.request.pretty_url.endswith("example.com/index.php"):
        resp = HTTPResponse(
            [1, 1], 200, "OK",
            Headers(Content_Type="text/html"),
            "<html><body>hello world</body></html>")
        flow.reply(resp)

但结果并不像预期的那样,在浏览器中显示为 http 状态代码,标题 och 正文为明文

[1,1] 200 OK
Content-Type: text/html

<html><body>hello world</body></html>

如何将其作为实际的“http”响应返回,以便 chrome 将其呈现为 html?

【问题讨论】:

    标签: mitmproxy


    【解决方案1】:

    sn-p 应该是这样的

    from mitmproxy import http
    
    
    def request(flow):
        if flow.request.pretty_url.endswith("example.com/index.php"):
            flow.response = http.HTTPResponse.make(
                200,
                "<html><body>hello world</body></html>",
                {"content-type":"text/html"},
            )
    
    

    对于较新版本的mitmproxy

    【讨论】:

    【解决方案2】:

    不要以http版本为例。将 [1, 1] 替换为“HTTP/1.1”

    from libmproxy.models import HTTPResponse
    from netlib.http import Headers
    
    def request(context, flow):
        if flow.request.pretty_url.endswith("example.com/index.php"):
            resp = HTTPResponse(
                "HTTP/1.1", 200, "OK",
                Headers(Content_Type="text/html"),
                "<html><body>hello world</body></html>")
            flow.reply(resp)
    

    【讨论】:

    【解决方案3】:

    您还可以捕获响应并编辑/替换它。

    使用 BeautifulSoup 也使事情变得更容易。

    我的解决方案是创建一个 html 文件 replace.html 并将其替换为原始响应:

    import mitmproxy
    from bs4 import BeautifulSoup
    
    def response(flow):
        if flow.request.pretty_host.endswith("example.com/index.php"):
            soup.BeautifulSoup(open("replace.html"))
            flow.response.content = str(soup).encode("utf8")
    

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 2021-05-10
      • 2019-07-23
      • 2013-11-02
      • 2013-12-13
      • 2017-04-30
      • 2017-03-11
      • 2019-10-28
      • 2021-08-27
      相关资源
      最近更新 更多