views:

143

answers:

2

I need a bash (or a plain shell) script to put in a cron job 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?

Thanks in advance.

EDIT: 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 only hosts.

should I also ping stackoverflow? I mean, if I can't access google wikipedia or stackoverflow I don't want internet :p

+3  A: 

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

Emil Vikström
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).
Joachim Sauer
+1  A: 

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.

amphetamachine