In this article, we are going to test IPv4’s connectivity and write scripts for it.
Prerequisites
Besides having a terminal open, we need to remember a few concepts:
- The If..Else condition case in shell scripting
- IP address of the device
curl
command must be installed (you can install it by using the following command:sudo apt install curl
)
The purpose of this section is to show you how you can check network connectivity.
How to do it
Open a terminal and create the test_ipv4.sh
script:
if ping -q -c 1 -W 1 8.8.8.8 >/dev/null; then
echo "IPv4 is up"
else
echo "IPv4 is down"
fi
Now, to test IP connectivity and DNS, create a script called test_ip_dns.sh
:
if ping -q -c 1 -W 1 google.com >/dev/null
then
echo "The network is up"
else
echo "The network is down"
fi
Lastly, create a script called test_web.sh
to test web connectivity:
case "$(curl -s --max-time 2 -I http://google.com | sed 's/^[^ ]* *\([0-9]\).*/\1/; 1q')" in
[23]) echo "HTTP connectivity is up";;
5) echo "The web proxy won't let us through";;
*) echo "The network is down or very slow";;
esac
How it works
- Execute the script as
$ bash test_ipv4.sh
. Here, we are checking the connection with the8.8.8.8
IP address. For that, we use theping
command in theif
condition. If the condition istrue,
we will get the statement written and printed on the screen as an if block. If not, the statement inelse
will be printed. - Execute the script as
$ bash test_ip_dns.sh
. Here, we are testing the connectivity using the hostname. We are also passing theping
command in theif
condition and checking if the network is up or not. If the condition istrue
, we will get the statement written in anif
block that’s printed on the screen. If not, the statement inelse
will be printed. - Execute the script as
$ bash test_web.sh
. Here, we are testing the web connectivity. We use thecase
statement here. We are using the curl tool in this case, which is used to transfer data to and from a server.
0 Comments