59

Each time, when I manually run tcpdump, I have to use Ctrl+C to stop it. Now I want to schedule my tcpdump with cronjob and I only need it to run for 1 and half hours. Without manually running Ctrl+C or kill command, how can it be stopped automatically? Here is the command I am testing:

tcpdump -i eth0 'port 8080' -w  myfile

I can schedule another cronjob to kill the tcpdump process, but it seems not a good idea.

Gary
  • 4,495
  • 13
  • 36
  • 49
  • Either of the answers for tcpdump; a solution that works for any program (unless they fiddle with SIGALRM)is the sigalarm program from http://www.superscript.com/signal/index.html – loreb Sep 08 '14 at 20:02

5 Answers5

86

You can combine -G {sec} (rotate dump files every x seconds) and -W {count} (limit # of dump files) to get what you want:

tcpdump -G 15 -W 1 -w myfile -i eth0 'port 8080'

would run for 15 seconds and then stop. Turn 1.5 hours into seconds and it should work.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
  • 37
    Note: this trick doesn't work if you're not receiving any traffic. – nibot Jul 24 '15 at 19:10
  • 1
    Yeah, tcpdump won't rotate, close or otherwise do anything until it gets a packet. – Yotam Alon Apr 01 '20 at 12:08
  • 3
    Use: `-w myfile-%Y-%m-%d_%H.%M.%S`. With `-w myfile`, tcpdump will keep overwriting the same file after specified number of seconds. You must provide a file name with time format specified by `strftime` in order to avoid overwriting. – rajneesh2k10 Dec 22 '20 at 17:47
81

you could use timeout

timeout 5400 tcpdump -i eth0 'port 8080' -w myfile
Matt
  • 919
  • 6
  • 2
23

You could do it like this:

tcpdump -i eth0 'port 8080' -w  myfile & 
pid=$!
sleep 1.5h
kill $pid
kiwisan
  • 449
  • 6
  • 16
5

The approach that worked best for me on Ubuntu 14.04

sudo -i
crontab -e

and then add the line

30 17 * * * /usr/sbin/tcpdump -G 12600 -W 1 -s 3000 -w /home/ubuntu/capture-file.pcap port 5060 or portrange 10000-35000

Notes

  • -G flag indicate number of second for dump to run, this example runs daily from 5:30 PM to 9:00 PM
  • -W is the number of iterations tcpdump will execute
  • Cron job will not be added until you save and exit the file
  • This example is for capturing packets of an Asterisk phone server
Ryan Charmley
  • 1,127
  • 15
  • 18
-5

You can use

watch tcpdump -i eth0 'port 8080' -w  myfile

This will run every 2 seconds.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
Raj RD
  • 91
  • 1
  • 3