30

Is there an easy way to check Internet connectivity from console? I am trying to play around in a shell script. One idea I seem is to wget --spider http://www.google.co.in/ and check the HTTP response code to interpret if the Internet connection is working fine. But I think there must be easy way without the need of checking a site that never crash ;)

Edit: Seems like there can be a lot of factors which can be individually examined, good thing. My intention at the moment is to check if my blog is down. I have setup cron to check it every minute. For this, I am checking the HTTP response code of wget --spider to my blog. If its not 200, it notifies me (I believe this will be better than just pinging it, as the site may under be heavy load and may be timing out or respond very late). Now yesterday, there was some problem with my Internet. LAN was connected fine but just I couldn't access any site. So I keep on getting notifications as the script couldn't find 200 in the wget response. Now I want to make sure that it displays me notification when I do have internet connectivity.

So, checking for DNS and LAN connectivity is a bit overkill for me as I don't have that much specific need to figure out what problem it is. So what do you suggest how I do it?

Here is my script to keep checking downtime for my blog:

#!/bin/bash

# Sending the output of the wget in a variable and not what wget fetches
RESULT=`wget --spider http://blog.ashfame.com 2>&1`
FLAG=0

# Traverse the string considering it as an array of words
for x in $RESULT; do
    if [ "$x" = '200' ]; then
        FLAG=1 # This means all good
    fi
done

if [ $FLAG -eq '0' ]; then
    # A good point is to check if the internet is working or not
        # Check if we have internet connectivity by some other site
        RESULT=`wget --spider http://www.facebook.com 2>&1`
        for x in $RESULT; do
            if [ "$x" = '200' ]; then
                FLAG=1 # This means we do have internet connectivity and the blog is actually down
            fi
        done

    if [ $FLAG -eq '1' ]; then
        DISPLAY=:0 notify-send -t 2000 -i /home/ashfame/Dropbox/Ubuntu/icons/network-idle.png "Downtime Alert!" "http://blog.ashfame.com/ is down."         
    fi  
fi

exit

This way I need to check for internet connectivity only where there is an issue with my blog response code. Its a bit heavy (as I am not using ping) but should not give any false positives. Right? Also how can I randomize pinging to a different site everytime, like facebook, google, yahoo etc. Also (I was trying to avoid any I/O) I can write to a log file by which I can check the count of downtime checks and then skip further checks till the site is down or cause longer checks (10mins instead of every min). What do you think?

  • "Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway. – João Pinto Feb 24 '11 at 23:43
  • In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :) – Ashfame Feb 25 '11 at 6:28

11 Answers 11

29

Checking whether specific website is up

First, multiple good online monitoring services are available. To pick one, Pingdom includes free account for monitoring one target. (Disclaimer: I am not affiliated with Pingdom in any way).

Second, using wget --spider for your own script is a good idea. You'll get some false positives when your computer is down, or when your DNS server is not working. Checking the return code is straightforward way to do implement this:

wget --spider --quiet http://example.com
if [ "$?" != 0 ]; then
  echo "Website failed!" | mail -s "Website down" your_email@provider.tld
fi

Yet again, there are shortcomings in this approach. If your provider has cached your DNS record, but the DNS server is down, others can't access your site even though monitoring says everything is fine. You can write short workaround with host, for example host example.com <your dns server IP>. That will return error if DNS server is not responding, even if OpenDNS or your own provider's DNS server works fine.

Checking whether internet is working

There isn't really easy way to handle this in every case.

You can for example run ping -c1 on multiple well known sites (for example www.google.com, facebook.com and ping.funet.fi) and check return codes to determine whether any destination is reachable. You can automatically check return code by using variable $?. Parameter -c1 is limiting number of ping packets to one.

You may encounter problems with some public wifis when there is a login gateway that redirects all pings and HTTP requests. If so, you may get ping responses and non-error HTTP status codes, even when you can't access any other sites.

If you want to check cable state, you can use

sudo ethtool eth0

From output (excerpt):

Speed: 1000Mb/s
Duplex: Full
Port: Twisted Pair
Link detected: yes

However, this is not telling whether you really have connectivity or not, just whether cable is connected and something is on other end.

  • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know? – Ashfame Feb 25 '11 at 6:39
  • 2
    ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests. – Olli Feb 25 '11 at 7:18
  • 1
    Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns. – djeikyb Feb 25 '11 at 8:56
  • For DNS checking you can of course use host (DNS query). It's very fast also. – Olli Feb 25 '11 at 9:38
  • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look – Ashfame Feb 25 '11 at 12:57
7

I'm using this method...

if [[ "$(ping -c 1 8.8.8.8 | grep '100% packet loss' )" != "" ]]; then
    echo "Internet isn't present"
    exit 1
else
    echo "Internet is present"
    wget www.site.com
fi
  • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that? – MERose Mar 3 '15 at 13:42
  • 2
    Note that this will fail in China and other countries that block Google – Tom J Nowell Jul 14 '18 at 14:24
7

I just used

nm-online

which pauses until a network connection is present by network manager. Worked well. You can do other stuff with it too.

5

Checking to see if a site is up is usually done with a monitoring tool like nagios. This will continuously monitor the site, and can notify you of outages.

When checking if the Internet is up from the command line I run through a number of steps:

  • Check Internet is up ping google.com (checks DNS and known reachable site).
  • Check web site is up use wget or w3m to fetch page.

If Internet is not up diagnose outward.

  • Check gateway is pingable. (Check ifconfig for gateway address.)
  • Check DNS servers are pingable. (Check /etc/resolv.conf for addresses.)
  • Check to see if firewall is blocking. (Check /var/log/syslog as I log blocks.)

If Internet is up but site is down check with w3m http://isup.me/example.com replacing example.com with the site that appears down. Use wget, lynx, or which ever command line browser you have available if you don't have the w3m browser installed.

  • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem – Ashfame Feb 27 '11 at 16:35
  • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then. – BillThor Feb 27 '11 at 16:58
  • you mean wget always return 1 for 200 HTTP response code? – Ashfame Feb 27 '11 at 20:08
  • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200. – BillThor Feb 27 '11 at 23:25
  • Thanks! That would make the script smaller and easy to understand. – Ashfame Feb 28 '11 at 5:24
4

This is the shell srcript I'm using to test for internet connectivity:

alarm.sh

#! /bin/bash

if curl --silent --head http://www.google.com/ |
    egrep "20[0-9] Found|30[0-9] Found" >/dev/null
then
    echo Internet status: OK
else
    echo Internet status: ERROR
    mpg321 alarm.mp3 &> /dev/null
fi
sleep 60
clear

./alarm.sh

You will need to install curl and mpg321

sudo apt-get install curl mpg321

You will need a .mp3 sound file renamed to alarm.mp3 in the same folder if you want audible alarm functionality. Finally configure website URL and egrep to your needs.

  • This works perfectly even when the user is behind a captive portal and has not logged in. – Ashhar Hasan May 8 '17 at 13:02
  • You can use egrep -q instead of egrep ... > /dev/null – wjandrea Nov 28 '17 at 2:26
  • Why does the script call itself instead of just using a while loop? – wjandrea Nov 28 '17 at 2:26
  • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better. – wjandrea Nov 28 '17 at 2:28
  • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself. – 01BTC10 Dec 1 '17 at 17:19
2

Checking whether internet is working

sudo nm-tool | grep "State: connected" | wc -l

From output (excerpt):

1 #System is connected to internet

However, as mentioned by others, this is not telling whether you really have connectivity or not. Eg. You could be connected to the router and router is not necessarily connected to internet.

  • 2
    nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]] – Six Jan 27 '16 at 15:15
  • @Six nmcli -f STATE -t nm the good thing is being independent of web sites! – Aquarius Power Jan 31 '16 at 2:13
  • 1
    Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet. – Sergiy Kolodyazhnyy Nov 28 '17 at 3:27
1

I am using this method:

if curl -s --head  --request GET www.google.com | grep "200 OK" > /dev/null ; then
    echo "Internet is present"
else
    echo "Internet isn't present"
fi

It will try to connect to a well-known website and if it can connect to it then we will assume there is the internet.

0

I needed help with the same question, and I got my answer this way:

echo $(nm-online) $? connection problems
  • how does this work? – wjandrea Nov 28 '17 at 2:31
  • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells. – Antonio Mar 3 '18 at 23:16
0

Checking whether Internet is working is not so trivial. ping is ICMP, so it might work even if the web proxy is down. Something similar occurs with DNS if you test with an IP.

Since my Internet connection is unstable I created this script (based on this one) that makes a gentle chord sound to call me, and also uses Ubuntu notify when the Internet connection comes back:

#!/bin/bash

hash play 2>&- || { echo >&2 "I require «play» but it's not installed. Try apt-get install sox. Aborting."; exit 1; }

WGET="`which wget`"
URL="http://www.google.com"
delay=3;
noConnectionMessage="No connection, trying again in $delay seconds...";
connectionMessage="WE HAVE INTERNET! :) Trying again in $delay seconds...";

echo "INTERNET TESTER: Type Ctrl+C to quit";
rm --force /tmp/index.site

function playSound {
    time=1;    # Time played
    if [ `sox --version| grep -oP "v[0-9.]+" | sed "s/[v.]//g"` -lt 1431 ]; then    #analize sox version, if greater than v14.3.1 can use pluck
        play -q -n synth $time sine;
    else
        play -q -n synth $time pluck $1;
        #for i in G4 G4 G4 E4;do play -n synth 0.1 pluck $i repeat 2;done    # You can play with something like this also :) (first three notes from Beethoven 5th symphony)
    fi
}

while [ 1 -eq 1 ]; do
    $WGET -q --tries=10 --timeout=2 $URL -O /tmp/index.site &> /dev/null
    if [ ! -s /tmp/index.site ];then
        echo $noConnectionMessage;
        #playSound E2
        sleep 1;
    else
        #~ zenity --warning --text "ADDRESS is back"
        notify-send -i "notification-network-wireless-full" "Connection state:" "$connectionMessage";
        echo $connectionMessage;
        playSound E3
    fi
    sleep $delay;
done

exit 0;
0

I was looking for a script that would continuously test my internet connection, that would be started whenever my server was up and I made this:

  1. First, install fping

    apt-get install fping
    
  2. Create an init script in the /etc/init.d folder with the following content (I called it testcon)

    #!/bin/bash
    
    PIDFILE=/var/run/testcon.pid
    
    . /lib/lsb/init-functions
    
    case "$1" in
      start)
            log_daemon_msg "Starting internet connection tester"
            /etc/init.d/testcond &
            echo $! > $PIDFILE
            log_end_msg $?
        ;;
      stop)
            log_daemon_msg "Stopping internet connection tester"
            PID=$(cat $PIDFILE)
            kill -9 "$PID"
            log_end_msg $?
        ;;
      *)
        echo "Usage: /etc/init.d/testcon {start|stop}"
        exit 1
        ;;
    esac
    
    exit 0
    
  3. Create a script in the /etc/init.d folder with the following content (I called it testcond)

    #echo Computer starting or testing daemon init
    while [ "$itest" == "" ] 
    do
        #wait 5 seconds 
        sleep 5
        itest=$(fping 8.8.8.8 | grep alive)
    done
    date | mail -s "Server is up and Internet is online" your_email@gmail.com
    
    #loop forever
    while [ "1" == "1" ] 
    do
        itest=$(fping 8.8.8.8 | grep alive)
        #if internet is down
        if [ "$itest" == "" ] 
        then
            #echo Internet is down
            #log time it was found down
            current_time=$(date)
            echo "Internet was found down @ $current_time" >> /mnt/data/Server/internet_log.txt
            #loop until it is back
            while [ "$itest" == "" ] 
            do
                #wait 60 seconds 
                sleep 60
                itest=$(fping 8.8.8.8 | grep alive) # test the internet
            done
            #when it is back
            current_time=$(date)
            echo "Internet is back        @ $current_time" >> /mnt/data/Server/internet_log.txt
            body=$(tail -2 /mnt/data/Server/internet_log.txt)
            echo "$body" | mail -s "Internet is back online" your_email@gmail.com
        fi
        #echo Internet is online
        #wait 60 seconds
        sleep 60
            done
    
  4. Then I run the commands below to add to the start-up:

    sudo update-rc.d testcon defaults
    sudo update-rc.d testcon enable
    
  5. Reboot

0

I was faced with random droppings of Wi-Fi connections by my Broadcom BCM94331CD chip. I devised the following bash script (infinite loop) checking each second if the Internet Wi-Fi connection is up and running. Other command line proposed here will wait for at least 5 to 10 seconds before closing with a status i.e. ping. In the mean time I am looking for a definitive solution as well.

From results on askubuntu, I will have to purge the bcmwl-kernel-source package as I use firmware-b43-installer and b43-fwcutter.

Thanks everyone for their suggestions (above).

This script needs to be added in the Start-Up Programs and don't need super user privilege to run as well.

#!/bin/bash
#

# Check if Wi-Fi is disabled e.g. 'out of range'
# If so quickly re-enable Wi-Fi
# Due to a problem with Broadcom proprietary driver in package firmware-b43-installer

# Script is part of Start-Up programs
# Stored in /usr/local/bin/
# Infinite loop checking every second if Wi-Fi is up and running

while true; do
  # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
  if [[ $(nmcli -f STATE -t g) != 'connected' ]]; then
    # Disable and Re-Enable Wi-Fi as the Wi-Fi is now 'out of range' (disconnected)
    nmcli radio wifi off
    nmcli radio wifi on
  fi
  sleep 1
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.