检查 shell 脚本中的连接

Check connection in shell script

我在 shell 脚本中使用 ping 检查连接。脚本如下。

ping -c 1 8.8.8.8 >> log.txt
if [ "$?" == "0" ] ; then
  echo "Success" >> log.txt
else
  echo "Failed" >> log.txt
fi

但有时即使网络正常也无法连接。所以我将 -c 选项更改为 5 而不是 1.

然后有时日志打印如下。

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=113 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=119 time=113 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=119 time=114 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=119 time=116 ms

--- 8.8.8.8 ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4001ms
rtt min/avg/max/mdev = 113.315/114.555/116.154/1.173 ms

“$?”仅包含上次尝试的结果。所以即使 ping 成功 4 次最后失败 1 次,脚本也会说连接失败。

我有一个想法,但不能写在 shell 脚本上,因为我对它不友好。

如果我用C++语言写,就变成这样

bool result = 1;
for(i=0; i<5; i++)
{
  [try ping and save return code at a]
  result = result&a;
}

if(result)
  cout >> "Success";
else
  cout >> "Failed";

所以这意味着我尝试 ping 5 次,如果有一个或多个 return 代码“0”,则打印“成功”。

如何使用 shell 脚本执行此操作?

您可以执行以下操作。当然,如果 ping 8.8.8.8 失败一次,我会说某处有问题!

status=Failure
for i in 1 2 3 4 5
do
  echo Attempt $i
  ping -c 1 8.8.8.8
  if [ "$?" == "0" ] ; then
    status="Success"
  fi
done
echo Status of ping test = $status

脚本说连接失败,因为您有一个 else 语句 echo "failed" >> log.txt 告诉脚本如果连接失败则回显失败。您可能会做一个 while read 循环来解析该文件 log.txt 并且只有在假设 5 个中有 3 个失败时才会抛出“失败”结果。

#!/bin/bash

ping -c 5 8.8.8.8.8 >> log.txt
if [ "$?" == "0" ] ; then
  echo "Success" >> log.txt
else
  echo "Failed" >> log.txt
fi

# Setting this variable to count the amount of occurances of Success
i=0
while read line
do
if [ $line == "Success" ]; then

        ((i=$i+1))
fi

#Telling bash if 'i' is greater than or equal 3 then it should echo success for the scripts output

if [ $i -ge 3 ]; then

        echo "Ping Script is successful" >> log.txt
else
        echo "Ping Script is failing :(" >> log.txt
fi

done >> log.txt

但是请注意,由于您是在此脚本的开头追加

ping -c 5 10.3.79.150 >> log.txt

这意味着该文件不会在每个 运行 脚本之后被清除。为避免此更改:

ping -c 5 10.3.79.150 >> log.txtping -c 5 10.3.79.150 > log.txt

有功能更好

#!/usr/bin/env sh

chk_ping ()
{
  # Set count with argument 1 or default 5
  count=${1:-5}
  # Perform count checks
  while [ $count -gt 0 ]
  do
    count=$(count - 1)
    # If it got a pong, it can return success
    if ping -qn4c1 8.8.8.8 >/dev/null
    then return
    fi
  done
  # It reaches here if all ping checks failed, so return failure
  return 1 # failure
}

if chk_ping 3
then
  echo 'successful ping'
else
  echo 'all pings failed'
fi

将结果相乘,在第一个0处中断,否则乘积为1

#!/bin/bash

limit=5
iter=1
totalSts=1
echo "Start" > log.txt
while [ $iter -le $limit ]
do
   ping -c 1 8.8.8.8 >> log.txt
   curSts=$?
   echo "iteration" $iter ":" $curSts
   totalSts=$((totalSts * curSts))
   if [ $totalSts -eq 0 ] ; then
     break
   fi
   iter=$((iter+1))
done

if [ $totalSts -eq 0  ] ; then
  echo "Success" >> log.txt
else
  echo "Failed" >> log.txt
fi