Bash script to check internet connection

#!/bin/bash

WGET="/usr/bin/wget"

$WGET -q --tries=10 --timeout=5 http://www.google.com -O /tmp/index.google &> /dev/null
if [ ! -s /tmp/index.google ];then
echo "no"
else
echo "yes"
fi



It tries to download google page within 5 seconds
returns 'yes' if google page index is downloaded
else return 'no'

5 comments:

Jean-Marc said...

Good idea.

But that will use some bandwidth. Will it be possible to have a "ping" solution?

Like pinging a website 10 times, and see how many packets reached the target?

JM

Anonymous said...

the best one

if eval "ping -c 1 www.google.com"; then
echo "We've got internet"
else
echo "No internet available"
fi

Anonymous said...

Nope the last one won't work so well. Because even if you don't have internet access the script will show that you have. I think ping in some way will leave exit status 0 even if it cant ping the host. Strange but seems to be true.

Anonymous said...

Sorry, scratch my last reply. Of course it seems to work. The thing was that even thou I hade switched my network connection of the script said that i had network connectivity. But after a while, like 30s it worked as it should. I became quite worried there for a while :P

Naresh Surampudi said...

$ cat server.txt
google.com
yahoo.com
redhat.com


$ cat pingalert.sh
#!/bin/bash
# Read the file line by line
cat server.txt | while read line
do
# check if there are no blank lines
if [ ! -z $line ]; then
PINGCOUNT=2
PING=$(ping -c $PINGCOUNT $line | grep received | cut -d ',' -f2 | cut -d ' ' -f2)
if [ $PING -eq 0 ]; then
echo "Something wrong with the server: $line"
# Or do send out mail
else
echo "All good: $line"
fi
fi
done


Output: $ ./pingalert.sh
All good: google.com
All good: yahoo.com
All good: redhat.com