Skip to content

Instantly share code, notes, and snippets.

@viniciusd
Last active August 2, 2019 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viniciusd/5174f8c289e85e9c706da5b27e4f863e to your computer and use it in GitHub Desktop.
Save viniciusd/5174f8c289e85e9c706da5b27e4f863e to your computer and use it in GitHub Desktop.
from datetime import datetime
import logging
import os
import subprocess
logger = logging.getLogger(__name__)
class TcpDump:
def __enter__(self):
now = int(datetime.now().timestamp())
self.pcap_name = '{}_pid{}.pcap'.format(now, os.getpid())
try:
self.proc = subprocess.Popen(
['tcpdump', '-w', self.pcap_name],
stderr=subprocess.DEVNULL
)
while now == int(datetime.now().timestamp()) and \
not os.path.isfile(self.pcap_name):
pass
logger.info("Running tcpdump")
except FileNotFoundError:
logger.warn("tcpdump is not available")
self.proc = lambda: None
self.proc.terminate = lambda: None
def __exit__(self, exc_type, *args):
self.proc.terminate()
if exc_type is None:
try:
os.remove(self.pcap_name)
except FileNotFoundError:
logger.warn("tcpdump pcap file does not exist")
else:
logger.warn("tcpdump pcap captured")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment