I have had some issues with my internet connection lately so I made some scripts to monitor it from my NAS.
First, let’s look at my network topology to understand what we want to test. I have my NAS attached via LAN to my modem with built in router, in other words we will only check LAN connectivity (not WLAN) to Internet.
The scripts I wrote will first see if router is reachable, and if it isn’t ping test is aborted (no point testing ISP connection if we can’t get to the modem). If router is reachable we will in parallel try to ping a set of hosts. Let’s look at the pinghost.sh script first:
#!/bin/sh host=$1 count=$2 SUCCESS=$(ping -c $count $host | tail -2 | head -1 | grep -c -e".* 0% packet loss.*") if [ "${SUCCESS}" -lt 1 ];then echo "${host} is dead at $(date)" fi
The script above will ping a host a number of times, and return an error string if there is packet loss. Example: pinghosts.sh google.com 1
will send one ping message to google.com. Now to the main script, pingtest.sh
#!/bin/sh COUNT=1 pinghostcommand="pinghost.sh" hosts="bbb-router 127.0.0.1 isp-gateway ping.sunet.se google.com ping.funet.fi" routerdead=$("${pinghostcommand}" bbb-router 1) if [ "X" = "X${routerdead}" ]; then for host in $hosts do $("${pinghostcommand}" $host $COUNT > "/tmp/$host") & done fi sleep 11 for host in $hosts do cat /tmp/$host | grep dead >> /samba-share/stats/pingStats.txt rm /tmp/$host done
With the above script set in crontab
# m h dom mon dow command
0,10,20,30,40,50 * * * * /samba-share/scripts/pingtest.sh
I can check the ping stats log file to see if my sampling indicates packet loss to what hosts and at what time.
cat /samba-share/stats/pingStats.txt | tail -n 10
google.com is dead at Wed Sep 19 21:30:07 CEST 2012
ping.funet.fi is dead at Wed Sep 19 21:30:07 CEST 2012
google.com is dead at Wed Sep 26 04:50:11 CEST 2012
google.com is dead at Wed Sep 26 05:10:12 CEST 2012
ping.sunet.se is dead at Sat Sep 29 08:00:12 CEST 2012
ping.funet.fi is dead at Sat Sep 29 08:00:12 CEST 2012
ping.sunet.se is dead at Sat Sep 29 19:20:12 CEST 2012
google.com is dead at Wed Oct 3 15:50:12 CEST 2012
ping.funet.fi is dead at Mon Oct 8 19:00:11 CEST 2012
ping.funet.fi is dead at Tue Oct 9 21:20:11 CEST 2012