大网数据广告活动
服务器运维问答

redirect output and log rotation

· 52CE 我爱测

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 ou…

问题原文

原帖链接 · pawel · CC BY-SA 3.0

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).

已采纳解答

原帖链接 · chicks · CC BY-SA 3.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-01-27)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。