2011年9月8日木曜日

rotating tcpdump

tcpdumpでネットワークのダンプを取り続ける際、任意のタイミングでダンプを保存するファイルを切り替えるシェルスクリプトです。なんか5回ぐらい同じシェルスクリプト書いて、さすがに飽きてきたので、そこそこ使いまわせるように書いたものをgistにおいておきました。

冒頭部分のNIC, FILTERを編集すればあとは深く考えずに使えるはずです。まあ、一瞬で読めるので、解説も何も無いですけど。。

2011.9.9追記
最近のtcpdumpにもrotate機能があると某氏からのご指摘。

tcpdump version 4.1.1のmanより。
-C     Before  writing  a  raw  packet to a savefile, check whether the file is currently larger
       than file_size and, if so, close the current savefile and  open  a  new  one.   Savefiles
       after  the  first  savefile  will have the name specified with the -w flag, with a number
       after it, starting at 1 and continuing upward.  The units of file_size  are  millions  of
       bytes (1,000,000 bytes, not 1,048,576 bytes).

-G     If  specified,  rotates  the  dump file specified with the -w option every rotate_seconds
       seconds.  Savefiles will have the name specified by -w which should include a time format
       as  defined by strftime(3).  If no time format is specified, each new file will overwrite
       the previous.

-Cオプションがファイルサイズベースのrotate、-Gオプションが時間ベースのrotateとのことです。-Gオプションはちゃんとファイル名に時間までいれてくれるらしいが、time formatは自分でstrftime書式で指定しないとダメらしいですね。たとえば

tcpdump -w /tmp/timed_dumps.%s -G 10

のように書くと

% ls /tmp/
timed_dumps.1315521248
timed_dumps.1315521259
timed_dumps.1315521270

というようにファイルが生成されていくようです。任意のタイミングではrotateできないけど、とても便利そうです。

#!/bin/zsh
PID_FILE=$HOME/local/var/run/`basename $0`.pid
NIC=en0
DATA_DIR=$HOME/local/var/data
FNAME_PREFIX="dump"
FILTER="port not 80"
if [ "`id -u`" != "0" ]
then
echo "need root privillege"
exit
fi
if [ $# -ne 1 ]
then
echo "syntax)" `basename $0` "[start|rotate|stop]"
exit
fi
mkdir -p `dirname $PID_FILE`
mkdir -p $DATA_DIR
stop () {
if [ -e $PID_FILE ]
then
kill `cat $PID_FILE`
rm $PID_FILE
fi
}
start ()
{
SUFFIX=`date "+%Y%m%d%H%M%S"`
tcpdump -s 0 -w $DATA_DIR/$FNAME_PREFIX-$SUFFIX.pcap -ni $NIC $FILTER 2> /dev/null &
disown
PID=$!
echo $PID > $PID_FILE
}
case $1 in
"start")
start
;;
"rotate")
stop
start
;;
"stop")
stop
;;
*)
echo "syntax)" `basename $0` "[start|rotate|stop]"
;;
esac
view raw dumper.sh hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿