This is a decorator to run tcpdump in the background while running a function. This way I can capture network traffic that my program is generating on the server. This was mostly an AI translation of my javascript decorator.
import subprocess
import time
from functools import wraps
def with_tcpdump(outfile='capture.pcap', iface='lo'):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
cmd = [
"/usr/sbin/tcpdump",
"-i", iface,
"-n",
"-A",
"port", "31438",
"-w", outfile
]
tcpdump = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Wait until tcpdump is listening
for line in tcpdump.stderr:
print(line, end='')
if "listening on" in line:
break
if "Permission denied" in line:
tcpdump.kill()
raise PermissionError("tcpdump permission denied")
time.sleep(0.3)
try:
fn(*args, **kwargs)
finally:
time.sleep(1.5)
tcpdump.terminate()
print("tcpdump stopped")
return wrapper
return decorator