如何使用 bash 测试 Internet 连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/929368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:14:08  来源:igfitidea点击:

How to test an Internet connection with bash?

bashconnectionping

提问by lauriys

How can an internet connection be tested without pinging some website? I mean, what if there is a connection but the site is down? Is there a check for a connection with the world?

如何在不 ping 某个网站的情况下测试互联网连接?我的意思是,如果有连接但站点已关闭怎么办?是否有检查与世界的联系?

回答by user3439968

Without ping

没有ping

#!/bin/bash

wget -q --spider http://google.com

if [ $? -eq 0 ]; then
    echo "Online"
else
    echo "Offline"
fi

-q: Silence mode

-q: 静音模式

--spider: don't get, just check page availability

--spider:不要,只需检查页面可用性

$?: shell return code

$? : 外壳返回码

0: shell "All OK" code

0:外壳“一切正常”代码

Without wget

没有 wget

#!/bin/bash

echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "Online"
else
    echo "Offline"
fi

回答by mateusza

Ping your default gateway:

Ping 你的默认网关:

#!/bin/bash
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error

回答by Jesse

Super Thanks to user somedrewfor their post here: https://bbs.archlinux.org/viewtopic.php?id=55485on 2008-09-20 02:09:48

超级感谢用户somedrew在此处发帖:https: //bbs.archlinux.org/viewtopic.php?id =55485 on 2008-09-20 02:09:48

Looking in /sys/class/net should be one way

查看 /sys/class/net 应该是一种方式

Here's my script to test for a network connection other than the loop back. I use the below in another script that I have for periodically testing if my website is accessible. If it's NOT accessible a popup window alerts me to a problem.

这是我的脚本,用于测试环回以外的网络连接。我在另一个脚本中使用以下内容,用于定期测试我的网站是否可访问。如果它不可访问,一个弹出窗口会提醒我有问题。

The script below prevents me from receiving popup messages every five minutes whenever my laptop is not connected to the network.

当我的笔记本电脑没有连接到网络时,下面的脚本阻止我每五分钟收到一次弹出消息。

#!/usr/bin/bash

# Test for network conection
for interface in $(ls /sys/class/net/ | grep -v lo);
do
  if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
done
if ! [ $OnLine ]; then echo "Not Online" > /dev/stderr; exit; fi

Note for those new to bash:The final 'if' statement tests if NOT [!] online and exits if this is the case. See man bash and search for "Expressions may be combined" for more details.

bash 新手请注意:最后的 'if' 语句测试是否为 [!] 在线,如果是这种情况则退出。有关更多详细信息,请参阅 man bash 并搜索“可以组合表达式”。

P.S. I feel ping is not the best thing to use here because it aims to test a connection to a particular hostNOT test if there is a connection to a networkof any sort.

PS 我觉得 ping 不是最好的方法,因为它旨在测试与特定主机的连接,而不是测试是否与任何类型的网络连接。

P.P.S. The Above works on Ubuntu 12.04 The /sys may not exist on some other distros. See below:

PPS 以上适用于 Ubuntu 12.04 其他一些发行版上可能不存在 /sys。见下文:

Modern Linux distributions include a /sys directory as a virtual filesystem (sysfs, comparable to /proc, which is a procfs), which stores and allows modification of the devices connected to the system, whereas many traditional UNIX and Unix-like operating systems use /sys as a symbolic link to the kernel source tree.[citation needed]

From Wikipedia https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard

现代 Linux 发行版包括一个 /sys 目录作为虚拟文件系统(sysfs,类似于 /proc,这是一个 procfs),它存储并允许修改连接到系统的设备,而许多传统的 UNIX 和类 Unix 操作系统使用/sys 作为内核源代码树的符号链接。[需要引用]

来自维基百科https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard

回答by legel

This works on both MacOSX and Linux:

这适用于 MacOSX 和 Linux:

#!/bin/bash

ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline

回答by paxdiablo

I've written scripts before that simply use telnet to connect to port 80, then transmit the text:

我之前写过脚本,只是简单地使用 telnet 连接到端口 80,然后传输文本:

HTTP/1.0 GET /index.html

followed by two CR/LF sequences.

后跟两个 CR/LF 序列。

Provided you get back some form of HTTP response, you can generally assume the site is functioning.

如果您得到某种形式的 HTTP 响应,您通常可以假设该站点正在运行。

回答by Luchostein

In Bash, using it's network wrapper through /dev/{udp,tcp}/host/port:

在 Bash 中,通过/dev/{ udp, tcp} / host / port使用它的网络包装器:

if echo -n >/dev/tcp/8.8.8.8/53; then
  echo 'Internet available.'
else
  echo 'Offline.'
fi

回答by Fuwan

The top answer misses the fact that you can have a perfectly stable connection to your default gateway but that does not automatically mean you can actually reach something on the internet. The OP asks how he/she can test a connection with the world. So I suggest to alter the top answer by changing the gateway IP to a known IP (x.y.z.w) that is outside your LAN.

最佳答案忽略了这样一个事实,即您可以与默认网关建立完美稳定的连接,但这并不意味着您实际上可以访问 Internet 上的某些内容。OP 询问他/她如何测试与世界的联系。因此,我建议通过将网关 IP 更改为 LAN 之外的已知 IP (xyzw) 来更改最佳答案。

So the answer would become:

所以答案会变成:

ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error

Also removing the unfavored backticks for command substitution[1].

还删除了命令替换[1] 中不受欢迎的反引号。

If you just want to make sure you are connected to the world before executing some code you can also use:

如果您只想确保在执行某些代码之前已连接到世界,您还可以使用:

if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
    # more code
fi

回答by WaiKit Kung

make sure your network allow TCP traffic in and out, then you could get back your public facing IP with the following command

确保您的网络允许进出 TCP 流量,然后您可以使用以下命令取回面向公众的 IP

curl ifconfig.co

回答by Chaminda Bandara

Execute the following command to check whether a web site is up, and what status message the web server is showing:

执行以下命令以检查网站是否已启动,以及 Web 服务器显示的状态消息:

$ curl -Is http://www.google.com |head -1 HTTP/1.1 200 OK

$ curl -Is http://www.google.com |head -1 HTTP/1.1 200 OK

Status code ‘200 OK' means that the request has succeeded and a website is reachable.

状态码“200 OK”表示请求成功并且可以访问网站。

回答by Francisc0

The top voted answerdoes not work for MacOS so for those on a mac, I've successfully tested this:

顶部投票答案因此对于那些在Mac上,我已经成功地测试了这并不适用于MacOS的工作:

GATEWAY=`route -n get default | grep gateway`
if [ -z "$GATEWAY" ]
  then
    echo error
else
  ping -q -t 1 -c 1 `echo $GATEWAY | cut -d ':' -f 2` > /dev/null && echo ok || echo error
fi

tested on MacOS High Sierra 10.12.6

在 MacOS High Sierra 10.12.6 上测试