How can I capture the last N seconds of packets using tcpdump?
I think the best way to accomplish this is with tcpdump's -G flag, which, when used with -w, will save your dump to a new file every N seconds. For instance:
tcpdump -w outfile-%s -G 10
This will create a new file with the name of 'outfile-XXXX' (where XXXX represents the number of seconds since epoch) every 10 seconds.
See the man pages for tcpdump(8) and strftime(3) for additional details.
I was trying to solve the same issue so, I wrote a portable script to run tcpdump for n second.
#tcpdump_for_n_sec.sh n=$1 shift #remove first arg from $@ tcpdump $@ & x=$! sleep $n kill $x
Usage ./tcpdump_for_n_sec.sh sec args for tcpdump
./tcpdump_for_n_sec.sh 5 i- any not port 22 -s0 -wfile.pcap