What automated ways are there of checking if the hosts in my /etc/hosts file are up?

link|improve this question
1  
Please consider adding this to the SysAdmin Tools Github project! brokenhaze.com/blog/2011/07/29/… – WesleyDavid Aug 10 '11 at 6:37
Oh, and the better way to do this is ask a clear question and then post the script as an answer and accept it. – WesleyDavid Aug 10 '11 at 6:39
@WesleyDavid github.com/Tom-Dignan/SysAdminTools done – Tom Dignan Aug 10 '11 at 6:41
Don't forget to do a pull request! George, the head of it, will appreciate it. – WesleyDavid Aug 10 '11 at 6:43
Thanks a lot, all done. – Tom Dignan Aug 10 '11 at 6:45
feedback

1 Answer

I made a solution. I'm posting it here because I really think others will want this. Also, do you have another way of doing this? Please share!

Edit: I have been informed this is not yet suitable for use on BSD.

#!/bin/bash
#
# Checks which hosts in your /etc/hosts file are up or down
#
# Author: Tom Dignan <tom.dignan@gmail.com>
#
# Contributors:
# - Janne Pikkarainen, grep optimization
# - Andy Lee Robinson, awk suggestion


ENABLE_IPV6=true
GREEN="\033[0;32m"
RED="\033[0;31m"
RESET="\033[0m"

#ipv4
grep -Ev '(^[#$]|::)' /etc/hosts | tr '\t' ' ' | \
cut -d ' ' -f1 | xargs -I@ echo ping -W2 -c1 @ '&>/dev/null' '&&' echo -e @ \
"\"[${GREEN}OK${RESET}]\"" '||' echo -e @ "\"[${RED}DOWN${RESET}]\"" | bash | awk '{ printf "%-22s %s\n", $1, $2 }'

if [ $ENABLE_IPV6 == true ]
then
    #ipv6
    grep "::" /etc/hosts | grep -v "^$" | tr '\t' ' ' | \
    cut -d ' ' -f1 | xargs -I@ echo ping6 -W2 -c1 @ '&>/dev/null' '&&' echo -e @ \
    "\"[${GREEN}OK${RESET}]\"" '||' echo -e @ "\"[${RED}DOWN${RESET}]\"" \
    | bash | awk '{ printf "%-22s %s\n", $1, $2 }'
fi

Now available on github, fork it here.

link|improve this answer
A nice little tool! A small suggestion about your cat | grep ... stanza: it probably could be replaced with grep -Ev "^([#$]|::)" /etc/hosts. Also note that *BSDs won't typically ship bash as their default shell, but use [t]csh instead, so at least the | bash part probably borks in the wonderful world of BSD, and the #!/bin/bash might make them angry. In FreeBSD bash goes to /usr/local/bin/bash if my memory serves me. – Janne Pikkarainen Aug 10 '11 at 6:58
Thanks. I'll set up a vm and get it to work. – Tom Dignan Aug 10 '11 at 7:07
@Janne added you to contributors and included your change – Tom Dignan Aug 10 '11 at 7:26
I feel so flattered. :-) – Janne Pikkarainen Aug 10 '11 at 7:35
+1 for niceness... but perhaps awk printf could be used to make the results line up for differing length hostnames – Andy Lee Robinson Aug 10 '11 at 7:55
show 4 more comments
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.