Skip to content

Instantly share code, notes, and snippets.

@tb3088
Last active October 4, 2017 22:23
Show Gist options
  • Save tb3088/3d0b541c47d7aa8e682d0ea4eb43f358 to your computer and use it in GitHub Desktop.
Save tb3088/3d0b541c47d7aa8e682d0ea4eb43f358 to your computer and use it in GitHub Desktop.
SSH wrapper
#!/bin/bash
# Usage:
#
# [VERBOSE=-v]
# [PROFILE=<profile>]
# [IDENTITY=<key>]
# ssh-wrapper.sh [cmd] <host> [args]
#
# just symlink to the wrapper to automatically set PROFILE
[ ${#@} -gt 0 ] || { >&2 echo ' insufficient arguments'; exit 1; }
case `uname -o` in
Cygwin*)
WHICH='\which --skip-functions --skip-alias'
;;
esac
: ${WHICH:=which}
: ${SSH:=`$WHICH ssh 2>/dev/null`}
: ${SCP:=`$WHICH scp 2>/dev/null`}
: ${SFTP:=`$WHICH sftp 2>/dev/null`}
: ${SCREEN:=`$WHICH screen 2>/dev/null`}
[ -x "$SSH" -a -x "$SCP" -a -x "$SFTP" ] || {
>&2 echo -e " missing binaries!\n SSH=$SSH\n SCP=$SCP\n SFTP=$SFTP\n"
exit 2;
}
# compute from wrapper filename
: ${PROFILE:=`basename -s .sh "$0"`}
# disable Screen
for s in ${NO_SCREEN:-git rsync}; do
[ "${PROFILE##*.}" = "$s" ] && { unset SCREEN; break; }
done
function _ssh() {
# environment:
# SCREEN - if set but empty, disable use of screen
# PROFILE - name of SSH configuration file (-F)
# IDENTITY - path to identity file (-i)
shopt -s extglob
local _screen _conf _ident _cmd
if [ "${TERM%.*}" = "screen" ]; then
_screen="$SCREEN";
TERM=${TERM/screen./}
TERM=${TERM/screen/}
# : ${TERM:=linux}
fi
if [ -n "$PROFILE" ]; then
for _conf in {,${HOME:-\~}/.ssh/}{,config{_,.}}"$PROFILE"; do
[ -r "$_conf" ] && break
done
[ -n "$_conf" ] || { >&2 echo "ERR! configuration ($PROFILE) not found"; return 1; }
fi
if [ -n "$IDENTITY" ]; then
for _ident in {,${HOME:-\~}/.ssh/}{,id_}"$IDENTITY"; do
[ -r "$_ident" ] && break
done
[ -n "$_ident" ] || { >&2 echo "ERR! identity ($IDENTITY) not found"; return 1; }
fi
_cmd=SSH
case ${1^^} in
SCP|SFTP)
_cmd=${1^^}
;&
SSH)
shift;
# disable Screen where persistent command output is helpful
unset _screen
;;
esac
${DEBUG:+set -x}
${_screen:+$_screen -t "${PROFILE:+${PROFILE#adfs-ftf-}:}$1" ${TERM:+-T $TERM}} \
${!_cmd} ${VERBOSE} ${_conf:+-F "$_conf"} ${_ident:+-i "$_ident"} "$@"
}
_ssh "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment