Skip to content

Instantly share code, notes, and snippets.

@andr1an
Last active February 1, 2018 08:48
Show Gist options
  • Save andr1an/41c52e0a91eb1541fe1efdb6ce3b325d to your computer and use it in GitHub Desktop.
Save andr1an/41c52e0a91eb1541fe1efdb6ce3b325d to your computer and use it in GitHub Desktop.
Parallel SSH commands execution in pure Bash
#!/usr/bin/env bash
#
# Example of parallel SSH execution with colorized hostnames.
# Requires a 256 color-compatible terminal.
#
set -u
declare -a SERVERS=(
my.server.001
my.server.002
)
COLORS="$(seq 9 2 229)"
ssh_logger() {
local host="$1"
local line
local color="$(shuf -en1 $COLORS)"
while IFS= read -r line; do
printf "[\e[38;5;${color}m%-44s\e[0m] $line\n" "$host"
done
}
pids=()
log=$(mktemp -t parallel_ssh.XXXXXXXXXX)
trap "rm -f $log" EXIT
for server in ${SERVERS[@]}; do
echo "==> Spawning SSH for $server <=="
ssh -A "$server" \
bash -c 'exec source ~/.bash_aliases; ls -l;' \
2>&1 | ssh_logger "$server" &>> $log &
pids+=($!)
done
echo
echo "Waiting ${pids[@]}..."
wait ${pids[@]}
echo
echo "==> LOG <=="
cat $log
# vim: ts=2:sw=2:et:sta:si
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment