ts=$(date +%Y-%m-%d-%H:%M:%S)
lockfile="/root/shell/lock.log"
if [ ! -d $lockfile ]
then
touch $lockfile
else
createts=`echo "$(ls -l /root/shell | grep lock | awk '{print$8}' | awk -F':' '{print$1}')*3600+$(ls -l /root/shell | grep lock | awk '{print$8}' | awk -F':' '{print$2}')"|bc`
nowts=`echo "$(date | awk '{print$4}' | awk -F':' '{print$1}')*3600+$(date | awk '{print$4}' | awk -F':' '{print$2}')*60+$(date | awk '{print$4}' | awk -F':' '{print$3}')" |bc`
long=$(expr $nowts - $createts)
if [ $long > 30 ]
then
rm -f $lockfile
if [ $? -ne 0 ];then
exit 0
fi
else
exit 0
fi
fi
file_name="log.txt"
echo "统计时间: ${ts}" >> $file_name
temp_file1="send.txt"
temp_file2="receive.txt"
total_file="total.txt"
iftop -Pp -Nn -t -L 100 -s 1 >$temp_file1
pragrom_list=(nginx redis-server )
numl=`echo "${#pragrom_list[@]}+2"|bc`
totalload=0
for i in ${pragrom_list[@]}
do
port_list=`netstat -plnt|grep $i|awk '{print $4}'|awk -F: '{print $2}'`
port_all=""
for port in $port_list
do
totalloop=0
port_all="${port}|${port_all}"
port_all=`echo $port_all|sed 's/\(.*\)|$/\1/g'`
done
if [[ $port_all == "" ]];then
continue
fi
send_load=`cat $temp_file1 |grep -E "${port_all}"|grep -E 'Mb|Kb'|grep '=>'|awk '{print $4}'|\tr '\n' '+' |sed -e s/Mb/*1000/g |sed s/Kb//g |sed 's/\(.*\)+$/\1\n/g'|bc`
if [[ ${send_load} == "" ]];then
send_load=0
fi
send_num=`cat $temp_file1 |grep -E "${port_all}"|grep "=>"|awk '{print $1}'`
echo "" > $temp_file2
for num in $send_num
do
cat $temp_file1 |grep '<='|sed -n ${num}p|grep -E 'Mb|Kb' >>$temp_file2
done
receive_load=`cat $temp_file2 |grep -E 'Mb|Kb'|awk '{print $4}'|\tr '\n' '+' |sed -e s/Mb/*1000/g |sed s/Kb//g |sed 's/\(.*\)+$/\1\n/g'|bc`
if [[ $receive_load == "" ]];then
receive_load=0
fi
total=`echo "${send_load}"+"${receive_load}"|bc`
echo "${i}总计 $total" >>$file_name
echo "${total}" >>$total_file
done
final_total=`cat $total_file | tr '\n' '+' | sed 's/^+\(.*\)+$/\1\n/g' | bc`
line=`awk 'END{print NR}' ${file_name}`
res=`echo "${final_total} > 100"|bc `
if [ $res -gt 0 ];then
sline=`echo "$(awk 'END{print NR}' log.txt)-${numl}" | bc`
eline=`awk 'END{print NR}' ${file_name}`
info=`sed -n "${sline},${eline}p" $file_name`
curl -X POST "https://api.telegram.org/bot645035919:AAG9qhGhnGfcFEMCSgBf_92doj5hzYTvMz8/sendMessage" -d "chat_id=-295819494&text=机器:$(ifconfig em1 |grep "inet addr" |awk '{print$2}') 警告!带宽使用总量:${final_total} KB 详细:${info}" >> /dev/null
fi
echo -e "\n" >>$file_name
echo > $total_file
rm -f $lockfile