获取ping回复并将其存储在bash变量中



我正在尝试使用ping命令获取跃点数我使用了一个循环来重复具有增量TTL值的命令但是我需要知道什么时候ping成功并且不是"ping";TTL在传输中过期";错误

success=0
counter=1
while [ $success == 0 ]; do
echo TTL: $counter
ping -n 1 google.com -i $counter
res=$?
if [[ $res == 0 ]]; then
success=1
fi
((counter++))
done
echo $counter

您需要这样的东西:

#!/bin/sh
BASE=`basename "$0" ".sh" `
DETAILS="`pwd`/${BASE}.details"
remote="google.com"
attempts="5"
interval="2"
watch="0"
while [ $# -gt 0 ]
do
case ${1} in
--host ) remote="$2" ; shift ; shift ;;
--monitor ) watch="1" ; shift ;;
--count ) attempts="$2" ; shift ; shift ;;
--interval ) interval="$2" ; shift ; shift ;;
* ) echo "n Invalid parameter used on the command line.  Valid options:  [ --host {} | --count {} | --interval {} | --monitor ]n Bye!n" ; exit 1 ;;
esac
done
if [ ${watch} -eq 1 ]
then
ping -c ${attempts} -i ${interval} ${remote} | tee "${DETAILS}"
echo ""
else
ping -c ${attempts} -i ${interval} ${remote} > "${DETAILS}"
fi
#pingformat
#64 bytes from lga34s34-in-f14.1e100.net (142.250.80.46): icmp_seq=5 ttl=58 time=20.2 ms
grep 'ttl=' "${DETAILS}" | awk -v host="${remote}" 'BEGIN{
count=0 ;
tTTL=0 ;
tRND=0 ;
}{
if( $1 != 0 ){
count++ ;
#Extract TTL
p=index( $0, "ttl=" ) ;
rem=substr( $0, p ) ;
sp=index( rem, " " ) ;
dat=substr( rem, 1, sp-1 ) ;
div=index( dat, "=" ) ;
ttl=substr( dat, div+1 ) ;
tTTL=tTTL+ttl ;
#Extract Round Trip Time
p=index( $0, "time=" ) ;
rem=substr( $0, p ) ;
sp=index( rem, " " ) ;
dat=substr( rem, 1, sp-1 ) ;
div=index( dat, "=" ) ;
rnd=substr( dat, div+1 ) ;
tRND=tRND+rnd ;
} ;
}END{
if( count == 0 ){
printf("t No response to ping for  %s .n", host ) ;
}else{
printf("t TTL [avg/%s] = %8.3fnt RND [avg/%s] = %8.3f ms for  %sn", count, tTTL/count, count, tRND/count, host ) ;
} ;
}'

相关内容

  • 没有找到相关文章

最新更新