How to start and kill tcpdump within a script?

36,964

I found part of the answer on this Stack Overflow post.

To summarize, tcpdump was buffering its output before writing to the output file, and this caused issues when the script attempted to interrupt it. Adding the -U ("flush") option to tcpdump fixes this.

Also necessary were a sleep command immediately after issuing tcpdump to allow it to initialize, and also before killing it, to allow it to write to the file:

#!/bin/bash  

#start a process in the background (it happens to be a TCP HTTP sniffer on  the loopback interface, for my apache server):   

tcpdump -U -i lo -w dump.pcap 'port 80' &   
sleep 5

#.....other commands that send packets to tcpdump.....

#now interrupt the process.  get its PID:  
pid=$(ps -e | pgrep tcpdump)  
echo $pid  

#interrupt it:  
sleep 5
kill -2 $pid

For reference, from man tcpdump, under the -U option:

If  the -w option is specified, make the saved raw packet output 
``packet-buffered''; i.e., as each packet is saved,
it will be written to the output file, rather than being written only
 when the output buffer fills.

After this, the script worked fine.

Share:
36,964

Related videos on Youtube

Life5ign
Author by

Life5ign

Updated on September 18, 2022

Comments

  • Life5ign
    Life5ign over 1 year

    Why can't I interrupt (i.e. kill -2, not kill -9) tcpdump as shown in this script? The script runs, but tcpdump does not terminate and continues to run at the command line, even after printing some of its exit output.

    (Note: this script requires sudo due to tcpdump and kill).

    #!/bin/bash  
    
    #start a process in the background (it happens to be a TCP HTTP sniffer on  the loopback interface, for my apache server):   
    
    tcpdump -i lo -w dump.pcap 'port 80' &  
    
    #.....other commands that send packets to tcpdump.....
    
    #now interrupt the process.  get its PID:  
    pid=$(ps -e | pgrep tcpdump)  
    echo $pid  
    
    #interrupt it:  
    kill -2 $pid
    
    • web.learner
      web.learner about 8 years
      I'm a little confused. Does the script work up until the kill part or does the initial tcpdump command take over and prevent anything after from running?
    • Life5ign
      Life5ign about 8 years
      the script works fine up until the kill part; echo $pid works..
    • Life5ign
      Life5ign about 8 years
      just found out that kill -9 $pid works, considering rephrasing the question, as I would like to interrupt and not kill the process..
  • Dustin Burke
    Dustin Burke over 6 years
    This is relevant if you had a continuous tcpdump running and wanted to end that process. Nothing else is affected.