正如後續:我放棄了監控tcp層上的流的想法。相反,我在python中編寫了一個代理,並讓我想監視的連接(一個http會話)通過此代理連接。結果更穩定,不需要root權限來運行。該解決方案取決於pymiproxy。
這進入獨立程序,例如, helper_proxy.py
from multiprocessing.connection import Listener
import StringIO
from httplib import HTTPResponse
import threading
import time
from miproxy.proxy import RequestInterceptorPlugin, ResponseInterceptorPlugin, AsyncMitmProxy
class FakeSocket(StringIO.StringIO):
def makefile(self, *args, **kw):
return self
class Interceptor(RequestInterceptorPlugin, ResponseInterceptorPlugin):
conn = None
def do_request(self, data):
# do whatever you need to sent data here, I'm only interested in responses
return data
def do_response(self, data):
if Interceptor.conn: # if the listener is connected, send the response to it
response = HTTPResponse(FakeSocket(data))
response.begin()
Interceptor.conn.send(response.read())
return data
def main():
proxy = AsyncMitmProxy()
proxy.register_interceptor(Interceptor)
ProxyThread = threading.Thread(target=proxy.serve_forever)
ProxyThread.daemon=True
ProxyThread.start()
print "Proxy started."
address = ('localhost', 6000) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey='some_secret_password')
while True:
Interceptor.conn = listener.accept()
print "Accepted Connection from", listener.last_accepted
try:
Interceptor.conn.recv()
except: time.sleep(1)
finally:
Interceptor.conn.close()
if __name__ == '__main__':
main()
從python helper_proxy.py
開始。這將創建一個代理監聽端口8080上的http連接,並監聽端口6000上的另一個python程序。一旦另一個python程序連接到該端口,代理將發送所有http回覆。這樣,助手代理可以繼續運行,保持http連接,並且可以重新啓動偵聽器進行調試。
以下是聽者的工作原理,例如listener.py
:
from multiprocessing.connection import Client
def main():
address = ('localhost', 6000)
conn = Client(address, authkey='some_secret_password')
while True:
print conn.recv()
if __name__ == '__main__':
main()
這將只打印所有回覆。現在將瀏覽器指向運行在端口8080上的代理,並建立您要監控的http連接。
感謝您的鏈接。我完全錯過了這個更新的pynids,我可以編譯這個版本。但首先測試表明,使用libnids只能捕獲新建立的tcp連接,因爲回調函數的工作方式(我需要捕獲正在進行的流)。那麼這不在這個問題的範圍之內...... – PiQuer 2012-01-06 16:27:53