shell-network/modules/remote.func

97 lines
2.2 KiB
Bash

#!/bin/bash
module_load ssh
remote_script () {
# usage: remote_script script -- <ssh setup options> host <ssh options>
# see ssh function
#
local sshargs;local user;local supass;local fn;
local OPTION
local OPTARG
local OPTIND
while getopts 'u:s:f:' OPTION; do
# echo OPTION $OPTION ARG $OPTARG
case "$OPTION" in
f)
# run a function within the script
fn=$OPTARG
;;
u)
# run command as another user
user=$OPTARG
;;
s)
# password of sudo account for running as root or other user
supass=$OPTARG
;;
*)
echo unknown remote script option -$OPTARG
return 1
;;
esac
done
shift $((OPTIND - 1))
local script=$1
[[ ! -f $script ]] && { echo cannot find script $script to run; return 1; }
[[ "$*" =~ "--" ]] && sshargs=$(sed 's/.*--\(.*\)/\1/' <<< "$@")
[[ ! $sshargs ]] && { echo must provide at least a hostname; return 3; }
# escape arguments with spaces
local i=2
local count=0
declare -a args
while [[ ! ${!i} = "--" ]]
do
#echo "${!i}"
args[count]=$(printf '%q' "${!i}")
count=$((count+1))
i=$((i+1))
done
# if script loads a module then use bundler
if [[ $(cat $script | grep module_load) ]]; then
echo bundling modules with script
local temp
module_load bundle
script=$( mktemp -t TEMP_FILE_script.XXXXXXXX )
bundle $1 $script
temp=true
fi
local _sudo
if [[ $user ]]; then
[[ ! $supass ]] && { echo password must be supplied for connecting sudo account. use -s;return 7; }
# echo running script remotely as user $user
_sudo="echo '${supass}' | sudo --stdin -u ${user} 2>/dev/null"
else
if [[ $supass ]]; then
_sudo="echo '${supass}' | sudo --stdin 2>/dev/null"
# echo running script remotely as root
fi
fi
src=$(cat $script)
if [[ $fn ]]; then
# echo running function
cmd="bash -c '$src; $fn ${args[*]}'"
else
# echo running as script
local sargs
[[ ${args[*]} ]] && sargs=$(printf '%s\n' "set -- ${args[*]}")
cmd="bash -c '$sargs; $(cat $script)'"
fi
ssh $sshargs "$_sudo" "$cmd"
[[ $temp ]]&& rm -f $script
}
# # if script was executed then call the function
(return 0 2>/dev/null) ||remote_script $@