Created
October 5, 2012 01:15
-
-
Save ralph-tice/3837496 to your computer and use it in GitHub Desktop.
run remote commands via bash/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
# Use this to run SSH Commands on a remote host. Arguments must be global variables before running runRemoteCmds() | |
# remoteHost string, required | |
# remoteUser string, required | |
# remoteKey string, optional | |
# remoteCmds array of strings, required | |
# | |
# Example: | |
# | |
# remoteHost="my.server.com" | |
# remoteUser="sshuser" | |
# remoteKey="~/.ssh/sshkeyfile.pem" | |
# remoteCmds=( "cd /var/www/html" "touch file.php" ) | |
# runRemoteCmds | |
## | |
function runRemoteCmds () | |
{ | |
local keyFile | |
local keyStr="" | |
local sshStr | |
local cmdStr | |
local counter=0 | |
# Make sure we have needed variables | |
if [ -z "$remoteHost" ]; then | |
echo 'remoteHost is not defined. Cannot run remote command(s)' | |
exit 1 | |
fi | |
if [ -z "$remoteUser" ]; then | |
echo 'remoteUser is not defined. Cannot run remote command(s)' | |
exit 1 | |
fi | |
if [ -n "$remoteKey" ]; then | |
# Expand special filename characters like ~ and * | |
keyFile=`eval echo $remoteKey` | |
if [ ! -r $keyFile ]; then | |
echo "SSH Key file $keyFile is not readable. Cannot run remote command(s)" | |
exit 1 | |
fi | |
keyStr="-i $keyFile" | |
fi | |
# Set up SSH Command string. The -o StrictHostKeyChecking=no ignores the "Continue connecting (yes/no)" prompt | |
sshStr="ssh $keyStr -l $remoteUser -o StrictHostKeyChecking=no -t -t $remoteHost" | |
# Disable BASH command expansion. Use -x to Enable | |
cmdStr='set +x;' | |
# Add newline after initial login | |
cmdStr=$cmdStr" echo;" | |
# Add commands to command string | |
while [ -n "${remoteCmds[$counter]}" ] | |
do | |
# Echo command first, then actually run it. | |
cmdStr=$cmdStr" echo '[$remoteUser]# ${remoteCmds[$counter]}'; ${remoteCmds[$counter]};" | |
# Add failure testing to this command (optional. Comment out to ignore failed commands) | |
cmdStr=$cmdStr' if [ $? -ne 0 ]; then echo "Last command returned an unsuccessful status code. Quitting."; exit 1; fi;' | |
(( counter++ )) | |
done | |
cmdStr=$cmdStr" exit;" | |
# Finally, send commands to SSH | |
echo $cmdStr | $sshStr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment