Exercise
Determining Host Status Exercise
Task
The finance application runs across several addresses and you have been asked which of them are actually answering. Write a script that checks each address and reports it as up or down.
- Host
servera- Script location
-
~/scripts/pinger.sh
-
Create a basic script file
Create the scripts directory, move into it, and open a new file.
mkdir -p ~/scripts cd ~/scripts vim pinger.shStart with the hashbang and a line that proves the script ran.
#!/bin/bash echo "Starting $0" -
Make it executable
chmod a+x pinger.sh ./pinger.sh -
Write a basic for loop
Store the addresses in a variable and loop over them. Three of these are on the lab network and two are not, which is what makes the report worth producing.
vim pinger.sh#!/bin/bash echo "Starting $0" finance_app_ips="172.25.250.9 19.19.19.18 172.25.250.10 19.19.19.19 172.25.250.11" for host in $finance_app_ips; do echo "Checking $host..." done./pinger.sh -
Branch on the result of ping
pingreturns0when the host answers and1when it does not. That number is exactly whatifreads.vim pinger.shfor host in $finance_app_ips; do echo "Checking $host..." if ping -c1 -W1 "$host"; then echo "$host is UP" else echo "$host is DOWN" fi done./pinger.sh -
Silence the ping output
Your report is buried in
ping's own output. Send that output to/dev/nullso only your report remains. The exit code is unaffected.vim pinger.shif ping -c1 -W1 "$host" > /dev/null; thenRead the finished script back, then run it.
cat pinger.sh ./pinger.shThe output is now a clean status report:
Starting ./pinger.sh Checking 172.25.250.9... 172.25.250.9 is UP Checking 19.19.19.18... 19.19.19.18 is DOWN Checking 172.25.250.10... 172.25.250.10 is UP Checking 19.19.19.19... 19.19.19.19 is DOWN Checking 172.25.250.11... 172.25.250.11 is UP -
Clean up
Remove the script.
rm ~/scripts/pinger.sh cd ~