How can I check Internet access using a Bash script on Linux? How can I check Internet access using a Bash script on Linux? linux linux

How can I check Internet access using a Bash script on Linux?


Using wget:

#!/bin/bashwget -q --tries=10 --timeout=20 --spider http://google.comif [[ $? -eq 0 ]]; then        echo "Online"else        echo "Offline"fi


If the school actually turns off their router instead of redirecting all traffic to a "why aren't you in bed" page, then there's no need to download an entire web page or send HTTP headers. All you have to do is just make a connection and check if someone's listening.

nc -z 8.8.8.8 53

This will output "Connection to 8.8.8.8 port 53 [tcp/domain] succeeded!" and return a value of 0 if someone's listening.

If you want to use it in a shell script:

nc -z 8.8.8.8 53  >/dev/null 2>&1online=$?if [ $online -eq 0 ]; then    echo "Online"else    echo "Offline"fi


Use:

#!/bin/bashINTERNET_STATUS="UNKNOWN"TIMESTAMP=`date +%s`while [ 1 ] do    ping -c 1 -W 0.7 8.8.4.4 > /dev/null 2>&1    if [ $? -eq 0 ] ; then        if [ "$INTERNET_STATUS" != "UP" ]; then            echo "UP   `date +%Y-%m-%dT%H:%M:%S%Z` $((`date +%s`-$TIMESTAMP))";            INTERNET_STATUS="UP"        fi    else        if [ "$INTERNET_STATUS" = "UP" ]; then            echo "DOWN `date +%Y-%m-%dT%H:%M:%S%Z` $((`date +%s`-$TIMESTAMP))";            INTERNET_STATUS="DOWN"        fi    fi    sleep 1 done;

The output will produce something like:

./internet_check.shUP   2016-05-10T23:23:06BST 4DOWN 2016-05-10T23:23:25BST 19UP   2016-05-10T23:23:32BST 7

The number in the end of a line shows duration of previous state, i.e. 19 up, 7 seconds down.