Bash 脚本(或多或少)可靠地检查互联网是否正常
我需要一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这似乎是一个很好的解决方案。只需添加更多主机,也许还有一些纯 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").
感谢您的代码,它工作得很好,实际上我只留下了一行:
Thanks for your code, it works great, I've left only one line actually:
您想要检查互联网连接的哪一部分?动态主机配置协议?域名系统?物理上插入插孔?内核识别网卡的存在吗?
您可以使用
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)
orifconfig(8)
.You can get detailed statistics about the interface using
ifstat
.