2010-08-04 4 views
1

내가 (에서 : http://blog.somethingaboutcode.com/?p=155) :이 코드를 실행 한 나는이를 얻고 나는이 얻을 127.0.0.1:8000에 갈 때마다트위스트 웹 프록시

from twisted.internet import reactor 
from twisted.web import http 
from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient 
from ImageFile import Parser 
from StringIO import StringIO 

class InterceptingProxyClient(ProxyClient): 
    def __init__(self, *args, **kwargs): 
     ProxyClient.__init__(self, *args, **kwargs) 
     self.image_parser = None 

    def handleHeader(self, key, value): 
     if key == "Content-Type" and value in ["image/jpeg", "image/gif", "image/png"]: 
      self.image_parser = Parser() 
     if key == "Content-Length" and self.image_parser: 
      pass 
     else: 
      ProxyClient.handleHeader(self, key, value) 

    def handleEndHeaders(self): 
     if self.image_parser: 
      pass #Need to calculate and send Content-Length first 
     else: 
      ProxyClient.handleEndHeaders(self) 

    def handleResponsePart(self, buffer): 
     print buffer 
     if self.image_parser: 
      self.image_parser.feed(buffer) 
     else: 
      ProxyClient.handleResponsePart(self, buffer) 

    def handleResponseEnd(self): 
     if self.image_parser: 
      image = self.image_parser.close() 
      try: 
       format = image.format 
       image = image.rotate(180) 
       s = StringIO() 
       image.save(s, format) 
       buffer = s.getvalue() 
      except: 
       buffer = "" 
      ProxyClient.handleHeader(self, "Content-Length", len(buffer)) 
      ProxyClient.handleEndHeaders(self) 
      ProxyClient.handleResponsePart(self, buffer) 
     ProxyClient.handleResponseEnd(self) 

class InterceptingProxyClientFactory(ProxyClientFactory): 
    protocol = InterceptingProxyClient 

class InterceptingProxyRequest(ProxyRequest): 
    protocols = {'http': InterceptingProxyClientFactory} 
    ports = {"http" : 80} 

class InterceptingProxy(Proxy): 
    requestFactory = InterceptingProxyRequest 

factory = http.HTTPFactory() 
factory.protocol = InterceptingProxy 

reactor.listenTCP(8000, factory) 
reactor.run() 

을 :

Traceback (most recent call last): 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", 
line 84, in callWithLogger 
    return callWithContext({"system": lp}, func, *args, **kw) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", 
line 69, in callWithContext 
    return context.call({ILogContext: newCtx}, func, *args, **kw) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p 
y", line 59, in callWithContext 
    return self.currentContext().callWithContext(ctx, func, *args, **kw) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p 
y", line 37, in callWithContext 
    return func(*args,**kw) 
--- <exception caught here> --- 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\selectr 
eactor.py", line 146, in _doReadOrWrite 
    why = getattr(selectable, method)() 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py" 
, line 460, in doRead 
    return self.protocol.dataReceived(data) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\protocols\basic. 
py", line 251, in dataReceived 
    why = self.lineReceived(line) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li 
ne 1573, in lineReceived 
    self.allContentReceived() 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li 
ne 1641, in allContentReceived 
    req.requestReceived(command, path, version) 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li 
ne 807, in requestReceived 
    self.process() 
    File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\proxy.py", l 
ine 147, in process 
    port = self.ports[protocol] 
exceptions.KeyError: '' 

을 할 때마다 나는 설치 파이어 폭스 또는 크롬이나 오페라 localhost에 프록시를 사용하려면 : 8000 프록시에 연결이 없습니다 (그리고 나는 더 이상 어떤 페이지에 연결할 수 있습니다, 왜냐하면 그것은 아마 프록시에 연결되어 있지 않기 때문일 것입니다).


좋아 여전히 실패하고 나는 로컬 호스트에서 프록시를 사용하는 파이어 폭스를 설정할 때 로깅 나는이 출력을 얻을 : 8000 및 로컬 호스트를 입력하여 같은 웹 브라우저 (에서 직접 프록시를 방문하지 않는 : 8000 파이어 폭스의 주소 표시 줄에)

2010-08-04 12:31:18-0400 [-] Log opened. 
2010-08-04 12:31:29-0400 [-] twisted.web.http.HTTPFactory starting on 8000 
2010-08-04 12:31:29-0400 [-] Starting factory <twisted.web.http.HTTPFactory inst 
ance at 0x010B3EE0> 
2010-08-04 12:33:55-0400 [-] Received SIGINT, shutting down. 
2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] (Port 8000 Closed) 
2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] Stopping factory <twiste 
d.web.http.HTTPFactory instance at 0x010B3EE0> 
2010-08-04 12:33:55-0400 [-] Main loop terminated. 

그러나 프록시를 직접 방문하면 키 오류가 발생합니다.

또한 스니핑을 할 수 없다. Wireshark는 localhost 트래픽을 스니핑하는 것처럼 보이지 않으며 피들러 2를 사용하면 자체 프록시를 설정하므로 더 이상 프록시 서버를 사용하지 않고 피들러 2의 프록시를 사용하기 때문에 작동합니다.

+0

[code] 태그를 사용하지 마십시오. 코드가되기 위해서는 텍스트 앞에 4 칸이 필요합니다. 여기에 + 붙여 넣기를하고 상자 위의 [1010101]을 선택하여 버튼을 누르십시오. 자동으로 4 개의 공백을 처리합니다. – avacariu

답변

1

KeyError 직접 연결했을 때 나타나는 예외는 프록시 요청에 상대 URL이 아닌 절대 URL을 포함해야한다는 사실 때문에 발생합니다. 브라우저가 프록시와 대화하고 있다는 것을 모르는 경우 /foo/bar과 같은 URL을 요청합니다. 프록시와 대화를한다는 것을 알고 있다면 대신 http://example.com/foo/bar과 같은 것을 요청할 것입니다. http://example.com/ 부분은 중요한 부분입니다. 왜냐하면 프록시가 그 정보를 알아 내고 검색해야하는 유일한 방법이기 때문입니다.

파이어 폭스, 크롬, 오페라가 프록시로 연결되면 프록시에 연결하지 않는 이유에 대해서는 설명하기가 더 힘듭니다. "HTTP 프록시"를 구성했는지 확인하고 다른 종류의 프록시는 지원하지 마십시오. 이를 두 번 확인한 후에 Wireshark와 같은 도구를 사용하여 네트워크 계층에서 발생하는 상황을보다 자세히 파악할 수 있습니다.

연결이 실제로 프록시에 만들어 졌을 수도 있지만 다른 것이 완료되지 못하게하는 잘못된 것이있을 수 있습니다. 이 경우 로깅을 사용하지 않으면 프록시가 단순히 출력을보고 연결을 수신하고 있음을 알 수 없을 수도 있습니다. 로깅을 활성화하려면 다음을 입력하십시오.

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

프록시 설정을 잘못 설정했습니다. IP 주소를 192.x.x.x 또는 10.x.x.x 또는 127.0.0.1 대신 localhost 또는 localhost로 설정하십시오. – Zimm3r