最近需要做一个实时统计网络情况并统计误包率的脚本,下面是StackExchange上的一个剽窃,虽然不完全满足,但只可以输出一些信息

#!/bin/bash

host=$

if [ -z $host ]; then
echo "Usage: `basename $0` [HOST]"
exit
fi while :; do
result=`ping -W -c $host | grep 'bytes from '`
if [ $? -gt ]; 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 # avoid ping rain
fi
done

[shell]判断网络情况并加上时间戳-LMLPHP

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 space
Host="www.baidu.com"
# no ping request
COUNT= #=== 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

结果

[shell]判断网络情况并加上时间戳-LMLPHP

05-11 18:20