neb/tools/spread.sh
2023-11-06 17:57:32 +01:00

70 lines
1.4 KiB
Bash
Executable file

#!/bin/bash
# spread command over multiple servers
SPREAD_SERVERS=${SPREAD_SERVERS:-}
SPREAD_SERVERS_FILE=${SPREAD_SERVERS_FILE:-servers.txt}
SPREAD_USER=${SPREAD_USER:-$USER}
SPREAD_COMMAND=${SPREAD_COMMAND:-}
while getopts "s:f:u:" opt; do
case $opt in
s)
SPREAD_SERVERS="$SPREAD_SERVERS $OPTARG"
;;
f)
SPREAD_SERVERS_FILE="$SPREAD_SERVERS_FILE $OPTARG"
;;
u)
SPREAD_USER="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
shift $((OPTIND - 1))
if [ -n "$1" ]; then
SPREAD_COMMAND="$@"
fi
if [ -f $SPREAD_SERVERS_FILE ]; then
SPREAD_SERVERS="$SPREAD_SERVERS $(cat $SPREAD_SERVERS_FILE)"
fi
if [ -z "$SPREAD_SERVERS" ]; then
echo "No servers specified"
exit 1
fi
if [ -z "$SPREAD_COMMAND" ]; then
echo "No command specified"
exit 1
fi
_ssh() {
ssh \
-l $SPREAD_USER \
-o ConnectTimeout=5 \
$1 \
"$SPREAD_COMMAND"
}
for server in $SPREAD_SERVERS; do
# while loop so we get:: $SPEAD_USER@$server: <output>
case ${SPREAD_LOG_STYLE:-prefixed} in
prefixed)
_ssh $server | while read -r line; do
printf "%s@%-10s: %s\n" "$SPREAD_USER" "$server" "$line"
done
;;
header)
printf "\n%s@%s\n---\n" "$SPREAD_USER" "$server"
_ssh $server
;;
*)
_ssh $server
;;
esac
done