Skip to content

Instantly share code, notes, and snippets.

@samv
Created February 19, 2015 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samv/3008f93c1e53a0a1c304 to your computer and use it in GitHub Desktop.
Save samv/3008f93c1e53a0a1c304 to your computer and use it in GitHub Desktop.
Script to reattach a shell to SSH
#!/bin/sh
# this script knows how to look in /tmp/ssh-* for SSH agent sockets.
# These are created by the SSH agent, or for hosts you connected to
# with 'ssh -A' (or you set 'ForwardAgent yes' in your .ssh/config).
# the upshot is that if *any* of your current ssh connections have an
# agent connection, then you can run this script and it will set your
# environment variables up in the shell you are currently working in.
# Finally, if it doesn't find any agents at all then it will start a
# new one.
# you might like to make this available via a shell alias, and put it
# in your .bash_profile or another similar location. If you pass "-q"
# as the first argument, it will not print anything. For instance,
# put it in your ~/bin, and then add to your .bashrc:
# Q=-q; [ -t ] && Q=; . bin/start-ssh-agent $Q
# alias ssha='. ~/bin/start-ssh-agent'
# Note, if the agent on the end of the socket has crashed/hung then
# the login shell may hang. You can usually press Ctrl+C to skip the
# rest of the script at that point and then 'killall ssh-agent'
if [ "$1" = "-q" ]
then
QUIET=1
shift
fi
PATTERN=$1
[ -z "$PATTERN" ] && PATTERN=:
OLD_SSH_AUTH_SOCK="$SSH_AUTH_SOCK"
SSH_AUTH_SOCK=
if [ -d "`ls -d /tmp/ssh-* 2>/dev/null | head -1`" ]
then
for x in "$OLD_SSH_AUTH_SOCK" /tmp/ssh-*/*
do
#echo -n Checking $x ...
[ -S $x ] || continue #( echo not a socket, ignoring; continue )
export SSH_AUTH_SOCK=$x
if [ -n "`ssh-add -l 2>/dev/null | grep \"$PATTERN\"`" ]
then
#echo that\'ll do!
found="$x"
break
#else
#echo no relevant identities, next!
fi
done
if [ -z "$found" ]
then
for x in "$OLD_SSH_AUTH_SOCK" /tmp/ssh-*/*
do
#echo -n Checking $x ...
[ -S $x ] || continue #( echo not a socket, ignoring; continue )
export SSH_AUTH_SOCK=$x
if [ -n "$(ssh-add -l 2>&1 | grep -i 'no identities')" ]
then
found="$x"
break
fi
done
fi
fi
if [ -z "$SSH_AUTH_SOCK" ]
then
#echo Starting a new agent, as \$SSH_AUTH_SOCK is \""$SSH_AUTH_SOCK"\"
eval $(ssh-agent -s 2>/dev/null)
fi
export SSH_AUTH_SOCK SSH_AGENT_PID
if [ -z "$QUIET" ]
then
echo "SSH_AUTH_SOCK is $SSH_AUTH_SOCK"
ssh-add -l
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment