Created
November 4, 2014 18:57
-
-
Save damonp/714f7f00da8dcc0cadde to your computer and use it in GitHub Desktop.
Simple script to check open ports on a remote host and restart via ssh/ansible if down.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Simple script to check open ports on a remote host and restart via ssh/ansible if down. | |
# Assumes using unique hostnames configured in /etc/ansible/hosts | |
# | |
if [ "$1" = "" ]; then | |
echo "Host and port(s) to check required." | |
echo "`basename $0` <hostname> <portlist>" | |
echo "`basename $0` host.domain.com 22,80,443,8080" | |
exit; | |
fi | |
if [ "$2" = "" ]; then | |
echo "Port(s) to check required." | |
echo "`basename $0` <hostname> <portlist>" | |
echo "`basename $0` host.domain.com 22,80,443,8080" | |
exit; | |
fi | |
fqdn=${1} | |
# host.domain.com get the hostname for ansible host resolution | |
host=`echo ${fqdn} | awk -F. '{ print $1 }'` | |
# ports assumed in a comma separated list (no space) 22,80,44,8080 | |
ports=${2} | |
# log stderr, stdout to $logfile | |
logfile=./check_ports.log | |
exec 3>&1 1>>${logfile} 2>&1 | |
# turn off globbing for breaking up port list. Set fieldspace character to ",". | |
set -f; IFS=, | |
# loop through list of ports | |
for port in ${ports}; do | |
# call netcat to scan for daemon listening on port | |
if ! nc -w 1 -z ${fqdn} ${port} 2>/dev/null ; then | |
echo "${host}:${port} DOWN" | tee /dev/fd/3 | |
case ${port} in | |
# restarting sshd | |
22) | |
ansible ${host} -m service -a "name=sshd state=restarted" | |
echo "${host}:${port} RESTARTED" | tee /dev/fd/3 | |
;; | |
# restarting web app | |
80,443,8080) | |
ansible ${host} -m service -a "name=nginx state=restarted" | |
ansible ${host} -m service -a "name=php-fpm state=restarted" | |
ansible ${host} -m service -a "name=varnishd state=restarted" | |
echo "${host}:${port} RESTARTED" | tee /dev/fd/3 | |
;; | |
# An elegant and automated port to service mapper would be nice here but given the | |
# intentions and simplicity of the script... considered it overkill. A couple of | |
# lines additional code for each port seems preferrable for the granularity above. | |
esac | |
else | |
echo "${host}:${port} UP" | tee /dev/fd/3 | |
fi | |
done | |
# reset globbing and fieldspace char. | |
set =f; unset IFS | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment