如何使用 ping 多个 IP 检查互联网连接

How to check internet connectivity using pinging multiple IP's

我需要一个 bash 脚本来检查互联网连接。 我先用了下面那个。

#!/bin/bash
#
while true; do
if ping -c 1 1.1.1.1 &> /dev/null
then
  echo "internet working"
else
  echo "no internet"
fi
sleep 5
done

它工作正常但有时会失败。所以我一直在寻找可以对多个 IP 进行 ping 测试的东西,这样只有一个 IP 必须成功 ping 才能假设连接。 我对 bash 非常陌生,如有任何错误,我深表歉意。

如何更正以下脚本使其按预期工作?

#!/bin/bash
#
while true; do 
count= '0'
if ping -c 1 1.1.1.1 &> /dev/null
then
count= '1'
fi

if ping -c 1 8.8.8.8 &> /dev/null
then
count= count + '1'
fi

if ping -c 1 www.google.com &> /dev/null
then
count= count + '1'
fi

if [ count -lt 1 ]
then
  echo "no internet"
else
  echo "internet working"
fi

sleep 5
done

在 if 语句中链接命令:

if ping -c 1 1.1.1.1 || ping -c 1 8.8.8.8 || ping -c 1 www.google.com
then
  echo "One of the above worked"
else
  echo "None of the above worked" >&2
fi

如果需要,您仍然可以重定向 ping 命令的输出。

if ping ... > /dev/null # redirect stdout
if ping ... 2> /dev/null # redirect stderr
if ping ... &> /dev/null # redirect both (but not POSIX) `>/dev/null 2>&1` is though.

我会为此任务使用一个函数,这样我就可以将要 ping 的主机作为参数传递:

#!/bin/bash

# Check internet connectivity
# Returns true if ping succeeds for any argument. Returns false otherwise
ckintconn () {
    for host
    do
        ping -c1 "$host" && return
    done
    return 1
} &>/dev/null

if ckintconn 1.1.1.1 8.8.8.8 www.google.com
then
    echo "internet working"
else
    echo "no internet"
fi