数据库服务器、图片服务器、提供FTP服务器等网卡的流量,一般都会比较大,为此我们非常有必要进行必要的监控措施,以便知晓网卡是否会成为瓶颈,以及可以建立网卡流量基准线,方便对比查看流量是否有异常。
通过shell脚本编写一小段代码实现查看网卡端口流量的效果:
1) 查看指定的某网卡端口的流量
2) 查看端口的流入值/流出值/总量值;
3) 指定二次观察端口流量的间隔时间和观察次数;
shell脚本network_top.sh实现的三种效果截图,如图所示:
1) 执行network_top.sh脚本无传递任何参数的错误提示信息
图1-1
2) 执行network_top.sh脚本传递错误参数的错误提示信息
图1-2
3) 执行network_top.sh脚本正确传递参数的采集数据效果图
图1-3
shell脚本network_top.sh的代码段
#!/bin/bash
#Name: network_top.sh
#Usage: sh network_top.sh --network-port=eth0 --interval-time=1 --repeat-total=10
#Description: monitor the network interface's flow
#WebSite: www.mysqlops.com
usage()
{
cat <<EOF
Usage: $0 [OPTIONS]
--network-port=ethN Show which network port,For Example --network-port=eth0.
--interval-time=N Every twice that need interval time,For Example --interval-time=1.
--repeat-total=N We need to see a continuous flow of card number,For Example --repeat-total=10.
EOF
exit 1
}
if [ "$#" -lt 1 ] ; then
usage
fi
for INPUT_DATA in $*
do
INPUT_DATA_1=$1
Val=`echo "$INPUT_DATA_1" | sed -e "s;--[^=]*=;;"`
case "$INPUT_DATA_1" in
--network-port=*)
ETH_PORT="$Val"
;;
--interval-time=*)
INTERVAL_TIME="$Val"
;;
--repeat-total=*)
REPEAT_TOTAL="$Val"
;;
*)
echo -e "\n ERROR VARIABLES: $INPUT_DATA_1 \n"
usage
exit 1
;;
esac
shift
done
infirst=$(cat /proc/net/dev |tr ':' ' '|awk '/'$ETH_PORT'/{print $2}')
outfirst=$(cat /proc/net/dev |tr ':' ' '|awk '/'$ETH_PORT'/{print $10}')
echo "$ETH_PORT" "in_bytes/sec" "out_bytes/sec" "total_bytes/sec" |awk '{printf("%10s %16s %16s %16s\n",$1,$2,$3,$4)}'
sleep $INTERVAL_TIME"s"
i=0
while [ "$i" -lt "$REPEAT_TOTAL" ]
do
inend=$(cat /proc/net/dev |tr ':' ' '|awk '/'$ETH_PORT'/{print $2}')
outend=$(cat /proc/net/dev |tr ':' ' '|awk '/'$ETH_PORT'/{print $10}')
sumin=$((($inend-$infirst)/$INTERVAL_TIME))
sumout=$((($outend-$outfirst)/$INTERVAL_TIME))
sum=$(($sumin+$sumout))
echo "$ETH_PORT" $sumin $sumout $sum |awk '{printf("%10s %16s %16s %16s\n",$1,$2,$3,$4)}'
infirst=$inend
outfirst=$outend
i=$(($i+1))
sleep $INTERVAL_TIME"s"
done