作为后续:我放弃了在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):
return data
def do_response(self, data):
if Interceptor.conn:
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)
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连接。