シェルスクリプトでLinuxサーバーのリアルタイムにネットワークの通信量を確認

1.コマンド関連

sed、awk、grep、iftop

 

2.サンプルコード:

#!/bin/sh
file_name="test.txt"
temp_file1="liuliang.txt"
temp_file2="liuliang2.txt"
iftop -Pp -Nn -t -L 100 -s 1 >$temp_file1
pragrom_list=(VueDaemon VueCenter VueAgent VueCache VueSERVER VUEConnector Myswitch Slirpvde)
#pragrom_list=(VueSERVER VueCenter)
>$file_name
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
port_all="${port}|${port_all}"
port_all=`echo $port_all|sed 's/\(.*\)|$/\1/g’`
done
if [[ $port_all == “" ]];then
echo “${i}sendflow=0" >> $file_name
echo “${i}receiveflow=0" >> $file_name
continue
fi
send_flow=`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`
#echo “cat liuliang.txt |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_flow} == “" ]];then
send_flow=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_flow=`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_flow == “" ]];then
receive_flow=0
fi
echo “${i}sendflow=${send_flow}" >>$file_name
echo “${i}receiveflow=${receive_flow}" >>$file_name
done

Source

Posted by arkgame