#!/bin/bash
# ssh - ssh command support library

set -e


######
# Settings

net_tool_ssh_config_init() {
	lib_setting_vars ssh_user
	lib_setting_vars --null ssh_host

	lib_setting_vars --null ssh_identity ssh_logfile

	lib_setting_vars ssh_background ssh_no_stdin ssh_no_login ssh_force_pty
	ssh_background=false
	ssh_no_stdin=false
	ssh_no_login=false
	ssh_force_pty=false

	lib_setting_arrays ssh_remote_portmap
}

net_tool_ssh_config_check() {
	ssh_user="${ssh_user:-$USER}"
}


######
# Internal functions

ssh_target() { echo "$ssh_user@$ssh_host"; }


######
# Public interface

run_ssh() {
	[ "$ssh_host" ] || error "run_ssh: \$ssh_host is not set"

	local -a opts=( )
	[ -z "$ssh_port" ] || opts+=( -p "$ssh_port" )

	if [ "$ssh_identity" ]; then
		[ -f "$ssh_identity" ] \
			|| error "$ssh_identity: SSH key file not found"
		opts+=( -i "$ssh_identity" )
	fi
	if [ "$ssh_logfile" ]; then
		file_mkdir "$ssh_logfile"
		opts+=( -E "$ssh_logfile" )
	fi

	! $ssh_background || opts+=( -f )
	! $ssh_no_stdin || opts+=( -n )
	! $ssh_no_login || opts+=( -N )
	! $ssh_force_pty || opts+=( -t )

	for map in "${ssh_remote_portmap[@]}"; do
		opts+=( -R "$map" )
	done

	opts+=( "$(ssh_target)" )
	run ssh "${opts[@]}" "$@"
}

run_ssh_sudo() {
	local ssh_force_pty=true
	run_ssh sudo -- "$@"
}

ssh_deploy_file() {
	has_args 2 "$@"
	local src=$1
	local dst=$2

	local temp rtemp
	temp=$(cmd_tempfile)
	rtemp=$(basename "$temp")

	run_sudo cat "$src" | run_ssh "cat >'$rtemp'"
	run_ssh_sudo mv "$rtemp" "$dst"
}

ssh_copy() {
	[ "$ssh_host" ] || error "$FUNCNAME: \$ssh_host is not set"
	local -a opts=( "${scp_opts[@]}" )
	[ -z "$ssh_port" ] || opts+=( -P "$ssh_port" )
	[ -z "$ssh_identity" ] || opts+=( -i "$ssh_identity" )
	run scp "${opts[@]}" "$@"
}

ssh_copy_to() { has_args 2 "$@"; ssh_copy "$1" "$(ssh_target):$2"; }
ssh_copy_from() { has_args 2 "$@"; ssh_copy "$(ssh_target):$1" "$2"; }

View the Script Reference Index


Generated on Tue Apr 25 21:21:08 PDT 2017 by mcsh i7 v0.18.0.