需要帮助编写一个扭曲的代理 [英] Need help writing a twisted proxy
问题描述
我想编写一个简单的代理,将请求页面正文中的文本打乱.我已经在 stackoverflow 上阅读了部分扭曲的文档和其他一些类似的问题,但我有点菜鸟,所以我仍然不明白.
I want to write a simple proxy that shuffles the text in the body of the requested pages. I have read parts of the twisted documentation and some other similar questions here on stackoverflow but I'm a bit of a noob so I still don't get it.
这就是我现在所拥有的,我不知道如何访问和修改页面
This is what I have now, I don't know how to access and modify the page
from twisted.web import proxy, http
from twisted.internet import protocol, reactor
from twisted.python import log
import sys
log.startLogging(sys.stdout)
class ProxyProtocol(http.HTTPChannel):
requestFactory = PageHandler
class ProxyFactory(http.HTTPFactory):
protocol = ProxyProtocol
if __name__ == '__main__':
reactor.listenTCP(8080, ProxyFactory())
reactor.run()
你能帮帮我吗?我很欣赏一个简单的例子(例如,向身体添加一些东西等等......).
Can you please help me out? I'd appreciate a simple example (e.g. add something to the body etc...).
推荐答案
我所做的是实现一个新的 ProxyClient,在我从 Web 服务器下载数据之后,在将数据发送到网络浏览器.
What I do is to implement a new ProxyClient, where I modify the data after I've downloaded it from the webserver, and before I send it off to the web browser.
from twisted.web import proxy, http
class MyProxyClient(proxy.ProxyClient):
def __init__(self,*args,**kwargs):
self.buffer = ""
proxy.ProxyClient.__init__(self,*args,**kwargs)
def handleResponsePart(self, buffer):
# Here you will get the data retrieved from the web server
# In this example, we will buffer the page while we shuffle it.
self.buffer = buffer + self.buffer
def handleResponseEnd(self):
if not self._finished:
# We might have increased or decreased the page size. Since we have not written
# to the client yet, we can still modify the headers.
self.father.responseHeaders.setRawHeaders("content-length", [len(self.buffer)])
self.father.write(self.buffer)
proxy.ProxyClient.handleResponseEnd(self)
class MyProxyClientFactory(proxy.ProxyClientFactory):
protocol = MyProxyClient
class ProxyRequest(proxy.ProxyRequest):
protocols = {'http': MyProxyClientFactory}
ports = {'http': 80 }
def process(self):
proxy.ProxyRequest.process(self)
class MyProxy(http.HTTPChannel):
requestFactory = ProxyRequest
class ProxyFactory(http.HTTPFactory):
protocol = MyProxy
希望这也适用于您.
这篇关于需要帮助编写一个扭曲的代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!