最近需要做一个实时统计网络情况并统计误包率的脚本,下面是StackExchange上的一个剽窃,虽然不完全满足,但只可以输出一些信息
#!/bin/bash host=$1 if [ -z $host ]; then echo "Usage: `basename $0` [HOST]" exit 1 fi while :; 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 33[0;31mdown 33[0m" else echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is 33[0;32mok 33[0m -`echo $result | cut -d ':' -f 2`" sleep 1 # avoid ping rain fi done
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%% ", 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%% ", 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 space Host="www.baidu.com" # no ping request COUNT=1 #=== Local vars (do not change them) # Cron-friendly: Automaticaly change directory to the current one cd $(dirname "$0") # Current script filename SCRIPTNAME=$(basename "$0") # Current date and time today=$(date '+%Y-%m-%d') currtime=$(date '+%H:%M:%S') #=== Main script while : do msg=$(ping -c $COUNT $Host | grep 'loss') echo -e "`date +'%Y/%m/%d %H:%M:%S'` ($Host 64Bytes) $msg" #>> plwatch.txt done
结果