Skip to content

Instantly share code, notes, and snippets.

@kerus1024
Created October 20, 2021 03:00
Show Gist options
  • Save kerus1024/da6a41410628a264d365848a93eea5cc to your computer and use it in GitHub Desktop.
Save kerus1024/da6a41410628a264d365848a93eea5cc to your computer and use it in GitHub Desktop.
bulk-command-remote.bash
#!/bin/bash
#
# Usage: ./bulk-command-remote.bash file <run_local_script.bash>
# ./bulk-command-remote.bash ping -c 1 8.8.8.8
#
key=~/private.key
default_username="ubuntu"
# "IP" "SSH-Port" "Username"
declare -a serverlist=(
"192.168.0.1" "22" "router-home"
"10.53.88.132" "8022" ""
)
serverlistnum=$(( ${#serverlist[@]} / 3 ))
param_arr=("$@")
param_str=""
start_index=$([ "$1" = "file" ] && echo 1 || echo 0)
for (( i = $start_index; i <= $# - 1; i++)); do
param_str="$param_str ${param_arr[$i]}"
done
if [ "1" = "$start_index" ]; then
is_file=1
if [ ! -f "$2" ]; then
echo "file $2 not exist"
exit 0
fi
param_str=$2
fi
for (( i = 0; i < serverlistnum; i++)); do
ip=${serverlist[$i * 3]}
port=${serverlist[$i * 3 + 1]}
_username=${serverlist[$i * 3 + 2]}
username=$([ -z "$_username" ] && echo $default_username || echo $_username )
echo "Index $i, $username@$ip:$port"
if [ "$1" = "file" ]; then
ssh -o "PreferredAuthentications=publickey" -o StrictHostKeyChecking=no -o LogLevel=ERROR -i $key -p $port $username@$ip "/bin/bash --norc --noprofile" < $param_str
else
ssh -o "PreferredAuthentications=publickey" -o StrictHostKeyChecking=no -o LogLevel=ERROR -i $key -p $port $username@$ip $param_str
fi
echo
echo
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment