Skip to content

Instantly share code, notes, and snippets.

@raffraffraff
Created January 28, 2017 13:27
Show Gist options
  • Save raffraffraff/f2df5bb127d275e697179cc354788efa to your computer and use it in GitHub Desktop.
Save raffraffraff/f2df5bb127d275e697179cc354788efa to your computer and use it in GitHub Desktop.
Run a script on remote hosts in batches
#!/bin/bash
# Name: multisshrun
# Purpose: Runs a script on remote hosts over ssh, in defined batch sizes
help() {
cat <<EOF
$(basename ${0}) accepts a host list via stdin and expects a script name as an argument
It runs the script on all host in batches, controlled by -j or --jobs (default=4)
Example:
$ cat /tmp/hostlist.txt | parallelize -j 5 script.sh
EOF
exit 1
}
until [ -z "$1" ]; do
case $1 in
-j|--jobs) shift; JOBS=$1; shift;;
*) SCRIPT=$1; shift;;
esac
done
JOBS=${JOBS:-4}
JOBDIR=$(mktemp -d)
mkdir -p "${JOBDIR}/results"
[[ ! -f "${SCRIPT}" ]] && help
RUNSLOT() {
local lock=${JOBDIR}/$1
local scriptname=$2
local targethost=$3
if [ $# -ne 3 ]; then
echo RUNSLOT expects 3 args, got $#
return 2
fi
if [ -f $lock ]; then
return 1
fi
touch $lock
(
scp -o StrictHostKeyChecking=no 2>/dev/null $scriptname $targethost:/tmp </dev/null >/dev/null
if [ $? -eq 0 ]; then
ssh 2>/dev/null -o StrictHostKeyChecking=no -t -t $targethost "sudo chmod +x /tmp/$(basename $scriptname); bash -c /tmp/$(basename $scriptname)" </dev/null >> ${JOBDIR}/results/${targethost}
else
echo -n ' [FAILED]'
fi
rm -f $lock
) & return 0
}
# MAIN LOOP
while read HOST; do
unset RESULT
until [ "${RESULT}" == "0" ]; do
for SLOT in $(seq 1 1 ${JOBS}); do
RUNSLOT $SLOT $SCRIPT $HOST
RESULT=$?
if [ ${RESULT} -eq 0 ]; then
echo " $HOST [slot:${SLOT}]"
break
fi
done
done
done
echo Results in ${JOBDIR}/results/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment