Search code examples
pythonsubprocesstcpdump

Getting the package statistic info from a tcpdump subprocess after terminating it


I'm using subprocess.Popen to perform tcpdump, which could collect the package information properly in my code.
After that, I would like to kill the tcpdump by another thread using os.kill(pid, signal.SIGKILL) and then record the relative packets statistic info.

In general, I'd like to get the statistic info as I run the tcpdump in bash:

  • packets captured
  • packets recieved by filter
  • packets dropped by kernel

I tried the cmd in following format:

proc=subprocess.Popen(shlex.split(tcpdump_cmd), 
                      stdouot=subprocess.PIPE, 
                      stderr=subprocess.PIPE)

However, I failed to get the statistic after kill the proc.pid by proc.stdout/stderr.readline().
I also tried to use:

fcntl.fcntl(fd.fileno().fcntl.F_SETFL,
            (fcntl.fcntl(fd.fileno.F_GETFL) | os.O_NDELAY | os.O_NONBLOCK))

none of them can output the statistic as what I expected. In addition, I tried shell=True, and shell=false - same result.

Is there a way I can achieve that? Thank you!

P.S. I found there were some topics relating to the tcpdump, unfortunately, as far as I know, I didn't find they can help me on this issue.


Solution

  • How are you killing the process?

    If this is a UN*X, then:

    • if you're killing it with SIGKILL, that will immediately terminate tcpdump and give it no chance to print the statistics, so there will be no statistics to read;
    • if you're killing it with SIGTERM or SIGINT, that will send it a signal that it catches, so it'll print the statistics before terminating.

    If this is Windows (so that you're using WinDump), you might not have a way to terminate it that gives it a chance to print the statistics.