【问题标题】:Python Proxy with Twisted带有 Twisted 的 Python 代理
【发布时间】:2012-08-01 18:01:21
【问题描述】:

你好!我有这个代码:

from twisted.web import proxy, http
from twisted.internet import reactor

class akaProxy(proxy.Proxy):
    """
    Local proxy = bridge between browser and web application
    """

    def dataReceived(self, data):

        print "Received data..."

        headers = data.split("\n")
        request = headers[0].split(" ")

        method = request[0].lower()
        action = request[1]
        print action
        print "ended content manipulation"  
        return proxy.Proxy.dataReceived(self, data)

class ProxyFactory(http.HTTPFactory):
    protocol = akaProxy

def intercept(port):
    print "Intercept"
    try:                
        factory = ProxyFactory()
        reactor.listenTCP(port, factory)
        reactor.run()
    except Exception as excp:
        print str(excp)

intercept(1337)

我使用上面的代码来拦截浏览器和网站之间的一切。在上面使用时,我将浏览器设置配置为:IP:127.0.0.1 和端口:1337。我将此脚本放在远程服务器中,以将我的远程服务器用作代理服务器。但是当我将浏览器代理 IP 设置更改为我的服务器时,它不起作用。我做错了什么?我还需要配置什么?

【问题讨论】:

    标签: python proxy twisted twisted.web


    【解决方案1】:

    大概您的dataReceived 在尝试解析传递给它的数据时引发了异常。尝试启用日志记录,这样您就可以看到更多正在发生的事情:

    from twisted.python.log import startLogging
    from sys import stdout
    startLogging(stdout)
    

    您的解析器可能引发异常的原因是dataReceived 不是仅在完整请求时才调用的。使用从 TCP 连接读取的任何字节调用它。这可能是一个完整的请求、一个部分的请求,甚至是两个请求(如果正在使用流水线)。

    【讨论】:

      【解决方案2】:

      dataReceived 在代理上下文中正在处理“将 rawData 转换为行”,因此尝试您的操作代码可能为时过早。您可以尝试改写allContentReceived,您将可以访问完整的标题和内容。这是一个我相信你所追求的例子:

      #!/usr/bin/env python
      from twisted.web import proxy, http
      
      class SnifferProxy(proxy.Proxy):
          """
          Local proxy = bridge between browser and web application
          """
      
          def allContentReceived(self):
              print "Received data..."
              print "method = %s" % self._command
              print "action = %s" % self._path
              print "ended content manipulation\n\n"
              return proxy.Proxy.allContentReceived(self)
      
      
      class ProxyFactory(http.HTTPFactory):
      
          protocol = SnifferProxy
      
      if __name__ == "__main__":
          from twisted.internet import reactor
          reactor.listenTCP(8080, ProxyFactory())
          reactor.run()
      

      【讨论】:

      • 我已将您的脚本复制并放置在我的远程服务器上,并在与服务器保持打开连接时运行它。然后我将浏览器的代理IP更改为我的服务器以访问ifconfig.me/ip,但我不能,浏览器显示“连接已超时”,服务器上打开的python脚本都没有显示任何信息。它保持原样。
      • 除了把你的浏览器代理设置改成你服务器的ip,还需要把代理端口设置成8080。
      • 首先尝试直接连接your-server-ip:8080(没有代理设置)。如果这可行,请确保除了将浏览器代理设置更改为服务器的 ip 之外,还将代理端口设置为 8080。如果直接连接不起作用,请检查您的服务器防火墙是否允许端口 8080,并且您的 LAN 不允许需要代理才能访问您的服务器的 ip
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      相关资源
      最近更新 更多