2011-01-23 154 views
9

我正嘗試在python中創建一個簡單的網頁過濾應用程序。我想這樣做的方式是監視端口tcp 80/443(http)上的流量,如果有流量,我想在我讓它通過之前檢查一些東西。如果檢查失敗,我希望將用戶重定向到我選擇的頁面。Python攔截來自瀏覽器的網頁流量

所以我的問題是,當用戶在瀏覽器中訪問http://www.google.com時,是否有一種方法可以攔截該請求,並且有什麼方法可以將它們重定向到我選擇的另一個頁面?

回答

7

您需要編寫一個Web代理,並將您的Web客戶端代理服務器設置爲http://localhost:8000/(或任何代理正在監聽)。然後

你的Web客戶端將發送HTTP這樣的:

GET http://www.google.com

到您的代理,它必須重新寫爲:

GET/

,併發送到www。 google.com,獲取響應,然後在原始套接字上將其發送回客戶端。請注意,解釋是大量簡化。

無論如何,它的所有標準的東西,我懷疑Python網絡代理已經存在,你可以入侵。

編輯:http://proxies.xhaus.com/python/

+1

謝謝比較。由於這是一個過濾器,如果我想確保沒有人禁用代理,我該怎麼做?有沒有辦法讓瀏覽器的默認目標留在我的代理中? – Sam 2011-01-24 17:20:38

3

這是從blog post我寫了一段時間回來。使用webob和粘貼。 TransparentProxy將請求轉發到請求指定的任何URL。您可以編寫中間件來在請求交給transparentproxy之前對請求執行某些操作。

然後,只需將您的瀏覽器代理設置設置爲您的代理正在運行的任何地址即可。

這個例子打印請求和響應,對於你的情況,你想檢查一個404或302的響應狀態或者任何和調度來編寫代碼。

from webob.dec import wsgify 
from paste import httpserver 
from paste.proxy import TransparentProxy 


def print_trip(request, response): 
    """ 
    just prints the request and response 
    """ 
    print "Request\n==========\n\n" 
    print str(request) 
    print "\n\n" 
    print "Response\n==========\n\n" 
    print str(response) 
    print "\n\n" 


class HTTPMiddleware(object): 
    """ 
    serializes every request and response 
    """ 

    def __init__(self, app, record_func=print_trip): 
     self._app = app 
     self._record = record_func 

    @wsgify 
    def __call__(self, req): 
     result = req.get_response(self._app) 
     try: 
      self._record(req.copy(), result.copy()) 
     except Exception, ex: #return response at all costs 
      print ex 
     return result 

httpserver.serve(HTTPMiddleware(TransparentProxy()), "0.0.0.0", port=8088) 

編輯:

這裏的中間件我寫的,所以我可以攔截的路徑,並返回不同的響應的例子。我使用它來測試一個爲生產硬編碼的JavaScript重度應用程序,我攔截了config.js並輸出了我自己的單元測試特定設置。

class FileIntercept(object): 
    """ 
    wsgi: middleware 
    given request.path will call wsgi app matching that path instead 
    of dispatching to the wrapped application 
    """ 
    def __init__(self, app, file_intercept={}): 
     self._app = app 
     self._f = file_intercept 

    def __call__(self, environ, start_response): 
     request = Request(environ) 
     if request.path.lower() in self._f: 
      response = request.get_response(self._f[request.path.lower()]) 
     else: 
      response = request.get_response(self._app) 
     return response(environ, start_response) 

,並作爲一個例子,我會初始化它像這樣....

app = FileIntercept(TransparentProxy(), 
          file_intercept={"/js/config.js":Response("/*new settings*/")}) 
httpserver.serve(HTTPMiddleware(app), "0.0.0.0", port=8088) 
0

如果它是一個特定的網站,如google.com,你總是可以poision hosts文件。這將是一個醜陋而簡單的解決方案。

如果它是一去,它位於:

C:/windows/system32/drivers/hosts.txt 

這也是在etc在Linux上,不能確定是雖然...