Просто как продолжение: я отказался от идеи контролировать поток на слое 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
.Это создаст прокси, прослушивающий http-соединения через порт 8080 и прослушивающий другую программу python на порту 6000. Как только другая программа 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-соединение, которое вы хотите отслеживать.