流量監控腳本
阿新 • • 發佈:2018-03-16
sort 流量監控 printf blog 獲取 %d IT else 但是
公司有臺服務器每天晚上流量很高,但是不知道確定是到哪個IP的流量
把改腳本定時到晚上執行
1 #!/bin/sh 2 nic=‘em1‘ 3 myFile=$nic‘monitor‘ 4 #iftop -P -n -N -t -B -L100 -s10 -i $nic | grep -Ev ‘Listening| Host|Total|total‘ | sed -e ‘s/=>//g‘ -e ‘s/<=//g‘ | grep -Ev ‘=|-‘ | sed -e ‘s/ [0-9]\{1,3\} //g‘ | sort -t‘.‘ -k1,1n -k2,2n -k3,3n -k4,4n > $nic5 if [ ! -f "$myFile" ]; 6 then 7 touch $myFile 8 fi 9 function KMG () 10 { 11 MB=`echo $1 |grep -Eo ‘KB|MB|GB|B‘` 12 NUM=`echo $1 |sed -e ‘s/K\|G\|M\|B//g‘` 13 if [ "$MB"x = "KB"x ];then 14 z=`echo $NUM | awk ‘{printf ("%.2f\n",$1 *1024)}‘` 15 elif [ "$MB"x = "MB"x ];then 16 z=`echo $NUM | awk ‘{printf ("%.2f\n",$1 *1024*1024)}‘` 17 elif [ "$MB"x = "GB"x ];then 18 z=`echo $NUM | awk ‘{printf ("%.2f\n",$1 *1024*1024*1024)}‘` 19 else 20 z=`echo $NUM` 21 fi 22 23 echo $z 24 25} 26 while true 27 do 28 29 iftop -P -n -N -t -B -L1000 -s10 -i $nic | grep -Ev ‘Listening| Host|Total|total‘ | sed -e ‘s/=>//g‘ -e ‘s/<=//g‘ | grep -Ev ‘=|-‘ | sed -e ‘s/ [0-9]\{1,3\} //g‘ | sort -t‘.‘ -k1,1n -k2,2n -k3,3n -k4,4n > $nic && echo `date "+%Y-%m-%d %H:%M:%S"` 30 ip=`cat $nic | awk ‘{print $1}‘` 31 for i in ${ip[@]} 32 do 33 #iftop獲取到的當前值,並判斷是否有冒號(沒有冒號會導致將有冒號的值也會計算) 34 t=`echo $i | grep -Eo ‘:‘` 35 if [ "$t"x = ":"x ];then 36 B=`grep -w $i $nic | awk ‘{print $5}‘` 37 #echo "1" $i $B 38 else 39 B=`grep -w $i $nic | grep -v ‘:‘ |awk ‘{print $5}‘` 40 #echo "2" $i $B 41 fi 42 43 #循環當前的值 44 for flow in ${B[@]} 45 do 46 A=`KMG $flow` 47 48 #判斷是否有冒號 49 50 if [ "$t"x = ":"x ];then 51 #判斷是否已經存在值,不存在直接寫入 52 #echo "1" $i $A 53 if grep -wq $i $myFile;then 54 KMGNUM=`grep -w $i $myFile | awk ‘{printf ("%.2f\n",$2 + A)}‘ A="$A"` 55 #echo ‘1‘ `grep $i $myFile` 56 sed -i "/$i/d" $myFile && echo $i $KMGNUM >> $myFile 57 #echo ‘2‘ `grep $i $myFile` 58 #echo $i $KMGNUM 59 #echo "A" $i $A 60 else 61 echo $i $A >> $myFile #&&echo "B" $i $A 62 fi 63 else 64 #判斷是否已經存在值,不存在直接寫入 65 #echo "2" $i $A 66 if grep $i $myFile | awk ‘{print $1}‘ | grep -v ‘:‘ | grep -q $i;then 67 KMGNUM=`grep -w $i $myFile | grep -v ‘:‘ | awk ‘{printf ("%.2f\n",$2 + A)}‘ A="$A"` 68 #echo ‘1‘ `grep $i $myFile| grep -v ‘:‘` 69 sed -i "/$i /d" $myFile && echo $i $KMGNUM >> $myFile 70 #echo ‘2‘ `grep $i $myFile| grep -v ‘:‘` 71 #echo $i $KMGNUM 72 #echo "A" $i $A 73 else 74 echo $i $A >> $myFile #&& echo "B" $i $A 75 #echo $i $A 76 fi 77 fi 78 done 79 done 80 done 81 82
使用方法
cat *monitor | sort -t ‘ ‘ -k2.1nr | sed -n ‘1,10p‘ | awk ‘{print $1,$2 /1024/1024 }‘
流量監控腳本