Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my school, the Internet is not available (every night after 23:00 the school will kill the Internet connection, to put us to bed >..<), Then the ping will never stop, though I have used the parameter ping -w1 ....

That is, when I use: ping -q -w1 -c1 8.8.8.8 to check if the Internet connection is up/down, it will be there without any output and doesn't exit, just like I am using a single cat.

I don't know why it's like this, But I think the problem is related to the school-internet-service. Any suggestion? (I think wget may be a good alternative, but how can I use it?)

like image 752
Libin Wen Avatar asked Jun 25 '13 07:06

Libin Wen


People also ask

How do I access internet through terminal in Linux?

Go to the terminal and type this command sudo apt-get install w3m w3m-img . Type Y when asked to confirm. Now wait; it's just a matter of 3 MBs. Whenever you want to open a web page, go to the terminal and type w3m wikihow.com , with your destination URL in the place of wikihow.com as needed.

How do I know if my server is connected to the internet?

Windows 11 lets you quickly check your network connection status. Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.

What is network Bash script?

Bash is a command language interpreter. Bash Script is a simple plain text file that lists a collection of commands that can be executed in the command line.


2 Answers

Using wget:

#!/bin/bash

wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -eq 0 ]]; then
        echo "Online"
else
        echo "Offline"
fi
like image 200
Atropo Avatar answered Sep 27 '22 20:09

Atropo


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>&1
online=$?
if [ $online -eq 0 ]; then
    echo "Online"
else
    echo "Offline"
fi
like image 36
Andrew Avatar answered Sep 27 '22 22:09

Andrew