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
  1. Create a basic script file

    Create the scripts directory, move into it, and open a new file.

    mkdir -p ~/scripts
    cd ~/scripts
    vim pinger.sh

    Start with the hashbang and a line that proves the script ran.

    #!/bin/bash
    echo "Starting $0"
  2. Make it executable

    chmod a+x pinger.sh
    ./pinger.sh
  3. 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
  4. Branch on the result of ping

    ping returns 0 when the host answers and 1 when it does not. That number is exactly what if reads.

    vim pinger.sh
    for 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
  5. Silence the ping output

    Your report is buried in ping's own output. Send that output to /dev/null so only your report remains. The exit code is unaffected.

    vim pinger.sh
        if ping -c1 -W1 "$host" > /dev/null; then

    Read the finished script back, then run it.

    cat pinger.sh
    ./pinger.sh

    The 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
  6. Clean up

    Remove the script.

    rm ~/scripts/pinger.sh
    cd ~