Last active
January 4, 2016 02:49
-
-
Save LukeHandle/8557208 to your computer and use it in GitHub Desktop.
Example script for Spigot Forums on controlling multiple servers over SSH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Specify the servers here in an array | |
serverip[0]="10.10.10.2" | |
serverip[1]="10.10.10.3" | |
serverip[2]="10.10.10.4" | |
serverip[3]="10.10.10.5" | |
serverip[4]="10.10.10.6" | |
serverip[5]="10.10.10.7" | |
# Specify the port the servers all use for SSH (too lazy to make it work | |
serverport[0]="2222" | |
serverport[1]="3333" | |
serverport[2]="4444" | |
serverport[3]="5555" | |
serverport[4]="6666" | |
serverport[5]="7777" | |
# This gets an integer of the number of array items and stores it as a variable | |
numservers=${#serverip[@]} | |
# This will port test the SSH port of the server and return a value depending upon the servers state. | |
ping_server() { | |
if [ -z "$1" ] ; then | |
# No variable sent, so exit (unlikely as this is a function) | |
exit 1 | |
else | |
if timeout 1 bash -c "echo >/dev/tcp/${serverip[$i]}/${serverport[$i]}" ; then | |
# Server is online, so return a 0 (okay) to whatever called this function. | |
return 0 | |
else | |
# Server is offline, so return a 1 (error) to whatever called this function. | |
return 1 | |
fi | |
fi | |
} | |
# This function will test the server and then run the command through SSH | |
run_cmd() { | |
# This sets a temporary variable ("i") to 0, each time it loops it then increments it (adds 1). Once "i" is greater than the number of server IPs it will move on (the function will be complete). | |
for ((i=0;i<$numservers;i++)); do | |
# If the server is available, do the SSH command | |
if ping_server ${serverip[$i]} ; then | |
echo "${serverip[$i]} is online:" | |
ssh -i ~/.ssh/id_rsa -p ${serverport[$i]} ${serverip[$i]} "$1" | |
else | |
# Tell the user the server is unavailable, but don't exit because the loop needs to continue | |
echo "${serverip[$i]} is offline" | |
fi | |
done | |
} | |
if [ -z "$1" ] ; then | |
# No argument sent, so exit. | |
echo "You must supply a command!" | |
exit 1 | |
else | |
# Send the argument to the function. | |
run_cmd "$1" | |
fi | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment