Last active
March 24, 2022 17:11
-
-
Save hnhnarek/99537629b5632e79e30b203fc5320b01 to your computer and use it in GitHub Desktop.
simple interface for using mitmproxt in python, (written in 10 minutes, so do not judge for code style&etc.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import random | |
import time | |
import socket | |
import json | |
import signal | |
import os | |
import signal, psutil | |
def kill_child_processes(parent_pid, sig=signal.SIGTERM): | |
try: | |
parent = psutil.Process(parent_pid) | |
except psutil.NoSuchProcess: | |
return | |
children = parent.children(recursive=True) | |
for process in children: | |
process.send_signal(sig) | |
class MitmPorxy: | |
def __init__(self,exec_path,proxy_str,host='localhost',port=None): | |
self.proxy_str = proxy_str | |
self.host=host | |
if port: | |
self.port = port | |
else: | |
#in case of multiple threads we can't fix port | |
self.port = random.randint(8080,8090) | |
self.har_file_prefix = str(time.time()) | |
self.command = '{0}/mitmdump -s "{0}/sc.py /tmp/out{3}.har" -p {1} -U {2} --insecure --no-upstream-cert'.format(exec_path,self.port,self.proxy_str,self.har_file_prefix) | |
self.har = {} | |
def start(self): | |
retry_count = 30 | |
retry_sleep = 0.5 | |
self.log_file = open('/tmp/mitm_proxy.log','a') | |
self.process = subprocess.Popen(self.command, | |
shell=True, | |
stdout=self.log_file, | |
stderr=subprocess.STDOUT) | |
count = 0 | |
while not self._is_listening(): | |
if self.process.poll(): | |
raise Exception('MitmProxy failed to start','failed to start check /tmp/mitm_proxy.log') | |
time.sleep(retry_sleep) | |
count += 1 | |
if count == retry_count: | |
self.stop() | |
raise Exception('MitmProxy failed to start','failed to start check /tmp/mitm_proxy.log') | |
def stop(self): | |
if self.process.poll() is not None: | |
return | |
try: | |
kill_child_processes(self.process.pid) | |
self.process.send_signal(signal.SIGTERM) | |
self.process.wait() | |
self.log_file.close() | |
except: | |
pass | |
retr_count = 10 | |
count = 0 | |
while not os.path.isfile('/tmp/out' + self.har_file_prefix + '.har'): | |
count += 1 | |
time.sleep(0.5) | |
if count > retr_count: | |
break | |
self.har = json.load(open('/tmp/out' + self.har_file_prefix + '.har')) | |
def _is_listening(self): | |
try: | |
socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
socket_.settimeout(1) | |
socket_.connect((self.host, self.port)) | |
socket_.close() | |
return True | |
except socket.error: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment