Total Hit Counter

Wednesday, November 23, 2011

Script to check traffic on network wise interface




Script to check traffic on network wise interface 

#!/bin/bash
######
#Created by Shankar Patel
#Create date : 21-11-2011
################################################################################

function help {
echo "The plugin will chekc the range of ip network.
Usage:
$0 <ip_network_range>
Please provide ip range as a argument.
examples:
$0 172.19
OK. sto: eth0 [up] | traffic_mit=1mb "
exit 3;
}

if [ "$1" = "" ]; then help ; fi

ipaddrs="$1"
interface=`ip addr | grep -v 'lo:' | grep $ipaddrs | grep 'scope global' |sed 's/ \+/ /g' | awk '{print $5$7$8}' | sed 's/secondary//g' | sed 's/scope//g' | cut -d':' -f1 | uniq`
DATA_DIR=`/usr/bin/dirname $0`
DATA_FILE=$DATA_DIR"/.iftraffic"_$interface"_"$1

input_data() {
NEW_DATA=$CUR_CHK_TIME":"$TOT_IN_MB":"$TOT_OUT_MB
echo $NEW_DATA > $DATA_FILE
chown nagios:nagios $DATA_FILE 2>/dev/null
}
exit_out() {
input_data
CUR_IN_MB=`echo "$TOT_IN_MB-$LAST_IN_MB" | bc`
CUR_OUT_MB=`echo "$TOT_OUT_MB-$LAST_OUT_MB" | bc `
echo "OK. $msg: $interface [up] | traffic_"$msg"_in="$CUR_IN_MB"MB traffic_"$msg"_out=$CUR_OUT_MB"MB
# echo $TOT_IN_MB $(($CUR_IN_MB/$(($CUR_CHK_TIME-$LAST_CHK_TIME))))
# echo $TOT_OUT_MB $(($CUR_OUT_MB/$(($CUR_CHK_TIME-$LAST_CHK_TIME))))
}

ip1=$(echo $ipaddrs | awk -F'.' '{print $1}')
ip2=$(echo $ipaddrs | awk -F'.' '{print $2}')
if [ "$ip1" -eq 172 ]; then
case $ip2 in
17)
msg="blr";;
18)
msg="adi";;
19)
msg="del";;
30)
msg="mum";;
esac
else
echo "UNKNOWN. ip range not found in plugin."
exit 3;
fi

old_data_fetch() {
if [ "`grep ':$' $DATA_FILE 1> /dev/null ;echo $?`" = "0" ] || [ "`grep '::' $DATA_FILE 1> /dev/null ;echo $?`" = "0" ]
then
input_data
fi
LAST_CHK_TIME=`cat $DATA_FILE | sed 's/:/ /g' | awk '{print $1}'`
LAST_IN_MB=`cat $DATA_FILE | sed 's/:/ /g' | awk '{print $2}'`
LAST_OUT_MB=`cat $DATA_FILE | sed 's/:/ /g' | awk '{print $3}'`
}
new_data_fetch() {
netstat -i > /tmp/.net_data
CUR_CHK_TIME=`date +%s`
if [ "$LAST_IN_MB" = "" ] ; then LAST_IN_MB=0 ; fi
if [ "$LAST_OUT_MB" = "" ] ; then LAST_OUT_MB=0 ; fi
MTU_D=`cat /tmp/.net_data | grep "$interface "| awk '{print $2}'`
BITS_D=`cat /tmp/.net_data | grep "$interface "| awk '{print $4}'`
CUR_IN_BIT=$(($MTU_D*$BITS_D))
TOT_IN_KB=$(($CUR_IN_BIT/8192))
TOT_IN_MB=`echo "scale=3 ; $TOT_IN_KB/1024" | bc`
BITS_D=`cat /tmp/.net_data | grep "$interface "| awk '{print $8}'`
CUR_OUT_BIT=$(($MTU_D*$BITS_D))
TOT_OUT_KB=$(($CUR_OUT_BIT/8192))
TOT_OUT_MB=`echo "scale=3 ;$TOT_OUT_KB/1024" | bc`
}
new_data_fetch
if [ ! -f $DATA_FILE ] ; then
input_data
echo "OK. Saving Initial values to File."
exit 0
fi
old_data_fetch
exit_out

No comments: