Python Twisted代理 - 如何拦截数据包 [英] Python Twisted proxy - how to intercept packets

查看:1516
本文介绍了Python Twisted代理 - 如何拦截数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python打印出HTTP响应的正文。

I'm trying to print out the body of a HTTP response using Python.

这是我的代码sofar:

Here is my code sofar:

from twisted.web import proxy, http
from twisted.internet import reactor
from twisted.python import log
import sys

log.startLogging(sys.stdout)

class ProxyFactory(http.HTTPFactory):
  protocol=proxy.Proxy

reactor.listenTCP(8080, ProxyFactory())
reactor.run()

当我连接浏览器时到localhost:8080,我可以看到我的所有请求都是通过本地运行的Python代理进行定向的。但是我如何1)打印出响应体并2)在将响应体发送回浏览器之前编辑它?

When I connect my browser to localhost:8080, I can see that all my requests are being directed through the Python proxy running locally. But how do I 1) print out response body and 2) edit the response body before sending it back to the browser?

我希望有人可以指出我正确的方向 - 请记住我是Python的新手!

I hope someone can point me in the right direction - please bear in mind that I'm very new to Python!

推荐答案

覆盖 dataReceived 方法的协议(在你的情况下是proxy.Proxy)并处理数据修改在那个方法中:

Override the dataReceived method of a protocol (proxy.Proxy in your case) and handle the data modification in that method:

from twisted.web import proxy, http
from twisted.internet import reactor
from twisted.python import log
import sys

log.startLogging(sys.stdout)

class MyProxy(proxy.Proxy):
    def dataReceived(self, data):

      # Modify the data here
      print data

      # perform the default functionality on modified data 
      return proxy.Proxy.dataReceived(self, data)

class ProxyFactory(http.HTTPFactory):
  protocol=MyProxy

factory = ProxyFactory()
reactor.listenTCP(8080, factory)
reactor.run()

这篇关于Python Twisted代理 - 如何拦截数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆