Bash script to (more or less) reliably check if the Internet is up
Asked Answered
A

3

11

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

Amidase answered 27/5, 2010 at 15:2 Comment(6)
Google is what I always use to test if I've got a connection.Moltke
8.8.8.8 would be good as well, especially since it's multicast.Instrumentality
The Internet as a whole is generally "up". However, your connection to it may not be! ;-)Notice
@John when I said internet is up i meant my connection is up, but you made a good point. :) If I wanted to know if the Internet is up I would have just pinged google ;)Mesocarp
#!/bin/sh is not Bash (even if sh is symlinked to bash).Participial
ups... I was going to do a bash script and then noticed that I could just do sh (which is usually more compatible) and forgot to put the right tag.Mesocarp
F
6

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").

Featherhead answered 27/5, 2010 at 15:7 Comment(1)
Actually depending on DNS functioning might be a good thing. If you want to check actual "I can browse the web like normal"-operation, then requiring DNS support is A Good Thing(TM).Jipijapa
W
4

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)
Warnock answered 3/5, 2013 at 10:48 Comment(0)
P
1

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.

Poster answered 27/5, 2010 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.