In: Computer Science
Assignment
Write a network diagnostics bash script that does the following:
The output of your script should look exactly like this (different numbers are OK). For the ping times output, use the 'avg' number from the ping command. This is the average that is calculated for you -- no need to calculate it in your script.
Ping time to default gateway: 0.348 ms Ping time to example.com: 24.807 ms Interface count: 2, and 2/2 are up There are 7 TCP ports in the LISTEN state
I have tried to be as descriptive as possible.
Here is the script :
#!/bin/sh
#here we get the ip of the default gateway.
default_ip=`ip route | grep default | awk '{print $3}'`
#now we ping to the default_ip address 5 times and store the avg
score
avg_default=`ping -c 5 $default_ip | grep rtt | awk '{print $4}' |
awk -F\/ '{print $2}'`
#We do the same for the example.com
avg_example=`ping -c 5 example.com | grep rtt | awk '{print $4}' |
awk -F\/ '{print $2}'`
#Here we get the interfaces available on the machine and store the
names in the variable 'interfaces'
interfaces=`ls -A /sys/class/net | grep -v lo`
#now we count the number of interfaces using word
count(wc).
num_interfaces=`ls -A /sys/class/net | grep -v lo | wc -l`
#we declare a variable for the interfaces that are up
initialized to 0.
up_interfaces=0
#this iterates over each interface
for i in $(seq 1 $num_interfaces)
do
#here we retrieve the i-th interface in the variable
'interfaces'
eth=`echo $interfaces | cut -d' ' -f $i`
#now we get the status of that interface
status=`cat /sys/class/net/$eth/operstate`
# if the interface is up then var 'up_interfaces' is
incremented
if [ "$status" = "up" ]
then
up_interfaces=$((up_interfaces+1))
fi
done
#Here we get the number of TCP ports that are open and are in
LISTEN state.
n=`netstat -anp | grep -w -c LISTEN`
echo "OUTPUT:"
echo "Ping time to default gateway: $avg_default ms."
echo "Ping time to example.com: $avg_example ms"
echo "Interface count: $num_interfaces, and $up_interfaces /
$num_interfaces are up."
echo "There are $n TCP ports in the LISTEN state."