Skip to content

Instantly share code, notes, and snippets.

@tbnorth
Last active October 2, 2025 19:46
Show Gist options
  • Save tbnorth/5d24739eb114c76948199819c59cb912 to your computer and use it in GitHub Desktop.
Save tbnorth/5d24739eb114c76948199819c59cb912 to your computer and use it in GitHub Desktop.
Multi-host execution util.

The script assumes:

a) you have something like defined:

export maindev=maindev
export bkupdev=bkupdev
export mainstg=mainstg
export bkupstg=bkupstg
export mainprod=mainprod
export bkupprod=bkupprod
export alldev="maindev bkupdev"
export allstg="mainstg bkupstg"
# Expansion is not recursive, can't use alllow="alldev allstg" here.
export alllow="maindev bkupdev mainstg bkupstg"

where the identify definitions are needed for dereferencing later, and, in .ssh/config

Host maindev
HostName dev.example.com
User me_who_else

Host bkupdev
HostName dev-reserve.example.com
User me_who_else

Then on alldev uname -n returns:

## On maindev: uname -n
dev.example.com     maindev
## On bkupdev: uname -n
dev-reserve.example.com     bkupdev

column -t is helpful for cleaning up output.

on -n will not append the host alias to each line of output.

on "host01 hostgroupB" will drop the user into a shell on each host in sequence.

#!/usr/bin/bash
SHOW_HOST=1
if [ "$1" == "-n" ]; then
shift
SHOW_HOST=""
fi
ON="$1"
shift
for TARGET in ${ON}; do
for HOST in ${!TARGET}; do
echo "## On $HOST: $@" >/dev/stderr
if [[ "x$@" == "x" ]]; then # No command, shell into each host.
ssh $HOST
elif [ -z "$SHOW_HOST" ]; then # -n - don't append host name to output
# First sed rule drops a long banner msg.
ssh $HOST $@ 2>&1 | sed -En '/^(In proceeding|1\) you are)/ d; p'
else # Append host name to each line of output.
ssh $HOST $@ 2>&1 | sed -En '/^(In proceeding|1\) you are)/ d; s/$/\t'$HOST'/; p'
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment