Categories
Network

Check If a Server Can Access the Internet with Linux Shell Script

Home » Network » Check If a Server Can Access the Internet with Linux Shell Script

When writing shell scripts, certain functionalities require ensuring that the server’s network can access the internet before proceeding. In such cases, you need a function to check the server’s network status. We can use curl to access www.google.com to determine if the server’s network is functioning properly.

How to Check If a Server’s Network Can Access the Internet Using a Linux Shell Script

You can run the following script to see if the server can access the internet.

<pre class="brush:bash;toolbar:false">#!/bin/bash
#test network
function network()
{
    local timeout=1
    #target website
    local target=www.google.com
    #get the response code
    local ret_code=`curl -I -s --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1`
    if [ &quot;x$ret_code&quot; = &quot;x200&quot; ]; then
        #The network is working fine
        return 1
    else
        #The network is not working
        return 0
    fi
    return 0
}
network
if [ $? -eq 0 ];then
echo &quot;The network is not working, please check your network settings!&quot;
exit -1
fi
echo &quot;The network is working fine, you can surf the internet!&quot;
exit 0</pre>

Script Execution Result When Network is Normal:

The network is working fine, you can surf the internet!

Script Execution Result When Network is Not Normal:

The network is not working, please check your network settings!

By Jaxon Tisdale

I am Jaxon Tisdale. I will share you with my experience in Network, AWS, and databases.

Leave a Reply

Your email address will not be published. Required fields are marked *