#!/bin/bash module_load ssh remote_script () { # usage: remote_script script -- host # see ssh function # local sshargs;local user;local supass;local fn;local args;local file [[ "$*" =~ "--" ]] && sshargs=$(sed 's/.*--\(.*\)/\1/' <<< "$@") [[ ! $sshargs ]] && { echo missing remote machine, must provide at least a hostname, -- hostname; return 3; } # reset arguments to just those before -- set -- $(sed 's/\(.*\)--.*/\1/' <<< "$@") local OPTION local OPTARG local OPTIND while getopts 'u:s:f:p:' OPTION; do # echo OPTION $OPTION ARG $OPTARG INDX $OPTIND case "$OPTION" in s) # script filename to run file=$OPTARG ;; f) # run a function within the script fn=$OPTARG ;; u) # run command as another user user=$OPTARG ;; p) # 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)) [[ ! $file ]] && { file=$1;shift 1; } if [[ ! -f $file ]]; then file=$(module_find $file) [[ ! $file ]] && { echo no module or script at $file to run; return 1; } fi # remaining script arguments args=$* # echo arguments for script: $args script=$file # 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 $file $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 $src'" fi # echo ssh $sshargs "$_sudo" "$cmd" ssh $sshargs "$_sudo" "$cmd" [[ $temp ]]&& rm -f $script } # can be used with a file or HEREDOC # todo test with < $file or with a pipe remote_stdin () { local file # echo args $@ file=$( mktemp -t TEMP_FILE_script.XXXXXXXX ) cat > $file echo remote_script -s "$file" "$@" #remote_script -s "$file" "$@" rm $file } # # if script was executed then call the function (return 0 2>/dev/null) ||remote_script $@