How to start and kill tcpdump within a script?
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.
Related videos on Youtube
Life5ign
Updated on September 18, 2022Comments
-
Life5ign over 1 year
Why can't I interrupt (i.e.
kill -2
, notkill -9
)tcpdump
as shown in this script? The script runs, buttcpdump
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 totcpdump
andkill
).#!/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 about 8 yearsI'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 about 8 yearsthe script works fine up until the kill part;
echo $pid
works.. -
Life5ign about 8 yearsjust found out that
kill -9 $pid
works, considering rephrasing the question, as I would like to interrupt and not kill the process..
-
-
Dustin Burke over 6 yearsThis is relevant if you had a continuous tcpdump running and wanted to end that process. Nothing else is affected.