使用tcpdump 對nginx的access.log 非400的ip進行自動抓包

#抓取nginx access日誌不是 400 的行,找出該ip ,而且啓動抓包
#該腳本的執行要放在 crond 裏面或者 while循環裏面
##################


#網卡名稱
net_card=enp0s8
#最多抓取10條記錄
cap_max_ip_num=1
#要抓取ip的在nginx裏面的錯誤

#存放抓包的目錄
cap_dir="/tmp/cap_dir/"
if [ ! -d "$cap_dir" ]; then
    mkdir "$cap_dir"
fi

#當前已經開始抓包的ip地址
cap_ip_history_file="$cap_dir/___tcp_dump_ip"
if [ ! -f "$cap_ip_history_file" ]; then  
  touch  "$cap_ip_history_file"  
fi 


function mytcpdump()
{
    ip=$1
    tcpdump -i $net_card -w $cap_dir/file${ip}.cap host $1 &
}

function begin_capture()
{
    count_line=`wc -l $cap_ip_history_file | awk '{print $1}'`
    if [ $count_line -ge $cap_max_ip_num ];then
        echo " capture max limit !!"
    exit 1
    fi

    ip=`tail -1 access.log |awk '{if($(NF-4)==400) print $1}'`
    echo "access the log is " $ip
    if [ "$ip" != "" ]; then
        grep_result=`grep "$ip" $cap_ip_history_file `
        if [ "$grep_result" == "" ]; then
            echo "begin tcp dump " $ip
            echo `date` $ip >> $cap_ip_history_file
            mytcpdump $ip
        fi
    fi
}


function clean()
{
    rm -rf $cap_dir
}


case "$1" in
    start)
        begin_capture
        ;;
    clean)
        clean
        ;;
    *)
        echo $"Usage: $0 {start|clean}"
        exit 1
esac
相關文章
相關標籤/搜索