While the answer that is accepted totally works, I'd like to just offer this script that might be useful should someone come across it.
Usage
So you would obviously need to change the lines under the "Echo $server $serverIP" lines to reflect the actual commands you'd like to use. $1 is the first thing you type after "./scriptname.sh" - e.g. ./scriptname.sh $1 $2 $3... - and here is how this breaks down:
$1 should be the file with your hostnames. $2 is the positional parameter you pass down to FunctionC (which always gets called in this example script). $2 and $3 can be used to call the other Functions (A/B) - alternatively you could replace $3 and $4 at the EOF with "FunctionA" and "FunctionB" if you always want to run them.
Hope this helps someone, it's been INVALUABLE to me whilst deploying packages or testing things across the domain.
#! /bin/bash
SVRList=`ls ./$1`
#========[ FUNCTIONS ]===============
FunctionA () {
for server in `cat $SVRList | grep -v ^#` # Makes variable "server" from each line in $SVRlist that is not commented
do
serverIP=$(nslookup $server | tail -2 | awk -F ":" '{print $2}')
echo "============= $server | $serverIP ============="
#command that you'd like to run locally
done
}
FunctionB () {
for server in `cat $SVRList | grep -v ^#`
do
passedvar="192.16.${1}"
serverIP=$(nslookup $server | tail -2 | awk -F ":" '{print $2}')
echo "============= $server | $serverIP ============="
ssh -q $serverIP '#command that you'd like to run remotely'
ssh -q $serverIP '#second command, if you so fancy'
ssh -q $serverIP "ping $passedvar"
#^ is done just to show an example of what can be done
done
}
FunctionC () {
for server in `cat $SVRList | grep -v ^#`
do
passedvar="192.16.${1}"
serverIP=$(nslookup $server | tail -2 | awk -F ":" '{print $2}')
echo "============= $server | $serverIP ============="
ssh -q $serverIP "ping $passedvar"
#^ is done just to show the power of positional parameters.
done
}
#========[ SCRIPT ]==========
if [ $# -lt 2 ]
then
printf "Usage: %s <file containing list of server hostnames> <passed variable> <functions> \n" "$(basename "$0")" >&2
exit 64
else
echo "Starting Script"
fi
FunctionC $2
$3
$4
exit
Also OP:
Why set service=httpd? It may be nicer to use [ testing and "service=$1" where $1 could be httpd, splunkd, or any other service. Additionally, the variable http_status should be changed to something like "service_status" to make the script better documented.
for
loop. Now I put those host names into an Ansible configuration file and tell Ansible to run a script on each of them. Ansible gives you the ability to write and test the script locally, then to run it remotely on each server. Half the stuff that my scripts used to do is handled by Ansible modules, so I have a lot less to maintain. A+, will never go back.salt \* cmd.run "systemctl is-active httpd"