Bash 脚本(或多或少)可靠地检查互联网是否正常

发布于 2024-09-02 20:47:27 字数 685 浏览 3 评论 0原文

我需要一个 Bash(或普通 shell)脚本来放入一个 cronjob,每分钟检查互联网是否正常。

我就是这样做的:

#! /bin/sh

host1=google.com
host2=wikipedia.org
curr_date=`date +"%Y%m%d%H%M"`

echo -n "${curr_date};"
((ping -w5 -c3 $host1 || ping -w5 -c3 $host2) > /dev/null 2>&1) && 
echo "up" || (echo "down" && exit 1)

你会怎么做?您会 ping 哪些主机?

说明:

  • 互联网已启动”是指我的互联网连接。

  • 通过“up”,我的意思是拥有可用的连接(如果我们谈论的是 DNS 关闭或连接真的很慢,那并不重要[注意 - w 表示超时])。这也是为什么我没有包含任何 IP,而只包含主机。

我还应该 ping Stack Overflow 吗?我的意思是,如果我无法访问 Google、维基百科或 Stack Overflow,我就不需要互联网 :p

I need a Bash (or a plain shell) script to put in a cronjob that every minute checks if the Internet is up.

This is how I did it:

#! /bin/sh

host1=google.com
host2=wikipedia.org
curr_date=`date +"%Y%m%d%H%M"`

echo -n "${curr_date};"
((ping -w5 -c3 $host1 || ping -w5 -c3 $host2) > /dev/null 2>&1) && 
echo "up" || (echo "down" && exit 1)

How would you do it? Which hosts would you ping?

Clarifications:

  • By "internet is up", I mean my internet connection.

  • By "up", I mean to have usable connection (doesn't really matter if we are talking about the DNS being down or the connection is really really slow [mind the -w for timeout]). That is also why I didn't include any IP but only hosts.

Should I also ping Stack Overflow? I mean, if I can't access Google, Wikipedia or Stack Overflow, I don't want Internet :p

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁与争疯 2024-09-09 20:47:27

这似乎是一个很好的解决方案。只需添加更多主机,也许还有一些纯 IP 主机,这样您就不必依赖 DNS 功能(这本身取决于您对“up”的定义)。

That one seems like a good solution. Just add a few more hosts, and maybe some pure IP hosts so you don't rely on DNS functioning (which in itself depends on your definition of "up").

九八野马 2024-09-09 20:47:27

感谢您的代码,它工作得很好,实际上我只留下了一行:

((ping -w5 -c3 8.8.8.8 || ping -w5 -c3 4.2.2.1) > /dev/null 2>&1) && echo "up" || (echo "down" && exit 1)

Thanks for your code, it works great, I've left only one line actually:

((ping -w5 -c3 8.8.8.8 || ping -w5 -c3 4.2.2.1) > /dev/null 2>&1) && echo "up" || (echo "down" && exit 1)
不知在何时 2024-09-09 20:47:27

您想要检查互联网连接的哪一部分?动态主机配置协议?域名系统?物理上插入插孔?内核识别网卡的存在吗?

您可以使用 host(1) 命令手动查询 ISP 的 DNS 服务器。这通常可以很好地表明您的路由器是否已失去与 ISP 的连接。

您可以使用 netstat(8)ifconfig(8) 查询内核有哪些接口。

您可以使用ifstat获取有关接口的详细统计信息。

What portion of Internet connectivity are you looking to check? DHCP? DNS? Physically being plugged into a jack? Kernel recognizing the presence of the NIC?

You can manually query your ISP's DNS server(s) by using the host(1) command. This is generally a good indication of whether your router has lost its connection to the ISP.

You can query what interfaces your kernel has by using netstat(8) or ifconfig(8).

You can get detailed statistics about the interface using ifstat.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文