最近需要做一个实时统计网络情况并统计误包率的脚本,下面是StackExchange上的一个剽窃,虽然不完全满足,但只可以输出一些信息
#!/bin/bashhost=$1if [ -z $host ]; then echo "Usage: `basename $0` [HOST]" exit 1fiwhile :; do result=`ping -W 1 -c 1 $host | grep 'bytes from '` if [ $? -gt 0 ]; then echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;31mdown\033[0m" else echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;32mok\033[0m -`echo $result | cut -d ':' -f 2`" sleep 1 # avoid ping rain fidone
ping google.com | awk '{ sent=NR-1; received+=/^.*(time=.+ ms).*$/; loss=0; } { if (sent>0) loss=100-((received/sent)*100) } { print $0; printf "sent:%d received:%d loss:%d%%\n", sent, received, loss; }'
ping google.com | awk '{ sent=NR-1; received+=/^.*(time=.+ ms).*$/; loss=0; } { if (sent>0) loss=100-((received/sent)*100) } { printf "sent:%d received:%d loss:%d%%\n", sent, received, loss }'
ping ... | sed -n -e 's/.*\(100% packet loss\).*/\1/p' \ -e 's_.*min/avg/max = [0-9]*/\([0-9]*\)/[0-9]*.*_\1_p'
统计每一帧的错误率
#!/bin/bash#=== PARAMETERS change them here# add ip / hostname separated by while spaceHost="www.baidu.com"# no ping requestCOUNT=1 #=== Local vars (do not change them)# Cron-friendly: Automaticaly change directory to the current onecd $(dirname "$0") # Current script filenameSCRIPTNAME=$(basename "$0") # Current date and timetoday=$(date '+%Y-%m-%d')currtime=$(date '+%H:%M:%S') #=== Main scriptwhile :do msg=$(ping -c $COUNT $Host | grep 'loss') echo -e "`date +'%Y/%m/%d %H:%M:%S'` ($Host 64Bytes) $msg" #>> plwatch.txtdone
结果