Skip to content

Instantly share code, notes, and snippets.

@qistoph
Created July 21, 2017 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qistoph/9e16577788e0c28c9fd27ed09b4fbdd2 to your computer and use it in GitHub Desktop.
Save qistoph/9e16577788e0c28c9fd27ed09b4fbdd2 to your computer and use it in GitHub Desktop.
Use SSH agent from other client
#!/bin/bash
# See blog for more details:
# https://qistoph.blogspot.nl/2017/07/use-ssh-agent-socket-from-remote-host.html
# Exit if undeclared variables are used
set -o nounset
# Exit if any command exits with error
set -o errexit
# Print each command to stdout before executing it
# set -o verbose
function enternum() {
if [ $# -lt 4 ]; then
echo "Invalid call to enternum (enternum $*)" >&2
return 1
fi
local __prompt=$1
local __min=$2
local __max=$3
local __resultvar=$4
if [ $__min -eq $__max ]; then
__prompt="$__prompt [$__min]"
else
__prompt="$__prompt [$__min-$__max]"
fi
while [ 1 ]; do
echo -n "$__prompt: "
read ans
[ -z "$ans" ] && [ $__min -eq $__max ] && ans="$__min"
if [[ $ans =~ ^[0-9]+$ ]]; then
if [[ $ans -ge $__min && $ans -le $__max ]]; then
eval $__resultvar="'$ans'"
return 0
fi
fi
done
}
# Setup SSH master channel
SSH_CONTROL_PATH="~/.ssh/control:%h:%p:%r"
LOCAL_SOCK="/tmp/ssh-auth-caret.$USER"
SSH_SERVER="$1"
ssh -N -f -M -o StreamLocalBindUnlink=yes -S "$SSH_CONTROL_PATH" "$SSH_SERVER"
ssh -S "$SSH_CONTROL_PATH" -O check "$SSH_SERVER"
exec 3< <(ssh -S "$SSH_CONTROL_PATH" "$SSH_SERVER" 'ls -1 /tmp/ssh-*/agent*')
SOCKS=()
while read -u 3 SOCK; do
echo "Sock :$SOCK"
SOCKS+=("$SOCK")
echo "${#SOCKS[@]}) $SOCK"
ssh -S "$SSH_CONTROL_PATH" "$SSH_SERVER" 'SSH_AUTH_SOCK="'"$SOCK"'" ssh-add -l'
echo
done
if [ ${#SOCKS[@]} -le 0 ]; then
echo "No sockets found on $SSH_SERVER" >&2
eval "$SAVED_OPTIONS"
exit 1
elif [ ${#SOCKS[@]} -eq 1 ]; then
socket=1
else
enternum "Socket" 1 ${#SOCKS[@]} socket
fi
ssh -N -f -S "$SSH_CONTROL_PATH" -L"$LOCAL_SOCK":"${SOCKS[$socket - 1]}" "$SSH_SERVER"
echo export SSH_AUTH_SOCK="$LOCAL_SOCK"
#ssh -S "$SSH_CONTROL_PATH" -O exit "$SSH_SERVER"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment