Bash – redirect output and log rotation

bashcrontcpdump

I need a bit of help with script / command / cronjob..

I need to redirect output of tcpdump command to logfile and keep 1 log file for each day. I know I could use tcpdump logging syntax but I'm also using awk -F to filter the output.
My command looks like this and run by itself works beautifully.

tcpdump -ieth0 -p "tcp[tcpflags] & (tcp-syn) !=0" | awk -F 'Flags' '{print $1}' > /var/log/tcpdump.log

How can I make it to rotate file for each day ? Is there any way to do with shell script (my shell scripting knowledge is very limited).

Best Answer

If you aren't good at shell scripting I wouldn't try to write your own log rotation. It doesn't sound like you've got any need here that wouldn't be handled better by using logrotate rather than rolling your own. You can make a simple config file

# /etc/logrotate.d/tcpdump
"/var/log/tcpdump.log" {
       daily
       rotate 30
       compress

       prerotate
            killall your_dump_script
       endscript

       postrotate
            your_dump_script &
       endscript
 }

This will:

  • rotate your file daily
  • keep 30 copies around since you don't want to fill up your drive
  • compress using gzip to save disk space. You can use zless or zgrep to view them.
  • kill your_dump_script before rotating and restart it after. Feel free to rename this to something more to your liking.

If you put it in /etc/logrotate.d this should get picked up by your built-in cron jobs, but if you want to run it manually to verify that it works:

logrotate /etc/logrotate.d/tcpdump

Or put the config in a different location and run it in from your script. Either way you're writing less code and things are more likely to work reliably.