Sharing the same `ssh-agent` among multiple login sessions
ssh -A [user@]remotehost
I think this might be what you're looking for. Use the -A switch when running ssh forward your ssh-agent. Here's a usecase:
I have a remote server that has some git repos on it with a remote pointing to github. Without an ssh-agent running in a screen session, I have to enter the passphrase for my key in order to do a "git pull origin master". Booo! In addition, I must have my private key installed on the remote server - more Boooo!
Instead, simply using ssh -A [user@]remotehost
passes along my locally running ssh-agent. Now, I no longer need my private key to even exist on the remote host. I don't believe you need to do any scripting at all with ssh-agent.
I might as well throw my own variation into the mix:
function sshagent_findsockets {
find /tmp -uid $(id -u) -type s -name agent.\* 2>/dev/null
}
function sshagent_testsocket {
if [ ! -x "$(which ssh-add)" ] ; then
echo "ssh-add is not available; agent testing aborted"
return 1
fi
if [ X"$1" != X ] ; then
export SSH_AUTH_SOCK=$1
fi
if [ X"$SSH_AUTH_SOCK" = X ] ; then
return 2
fi
if [ -S $SSH_AUTH_SOCK ] ; then
ssh-add -l > /dev/null
if [ $? = 2 ] ; then
echo "Socket $SSH_AUTH_SOCK is dead! Deleting!"
rm -f $SSH_AUTH_SOCK
return 4
else
echo "Found ssh-agent $SSH_AUTH_SOCK"
return 0
fi
else
echo "$SSH_AUTH_SOCK is not a socket!"
return 3
fi
}
function sshagent_init {
# ssh agent sockets can be attached to a ssh daemon process or an
# ssh-agent process.
AGENTFOUND=0
# Attempt to find and use the ssh-agent in the current environment
if sshagent_testsocket ; then AGENTFOUND=1 ; fi
# If there is no agent in the environment, search /tmp for
# possible agents to reuse before starting a fresh ssh-agent
# process.
if [ $AGENTFOUND = 0 ] ; then
for agentsocket in $(sshagent_findsockets) ; do
if [ $AGENTFOUND != 0 ] ; then break ; fi
if sshagent_testsocket $agentsocket ; then AGENTFOUND=1 ; fi
done
fi
# If at this point we still haven't located an agent, it's time to
# start a new one
if [ $AGENTFOUND = 0 ] ; then
eval `ssh-agent`
fi
# Clean up
unset AGENTFOUND
unset agentsocket
# Finally, show what keys are currently in the agent
ssh-add -l
}
alias sagent="sshagent_init"
And then every time I log in, if I want an agent attached (which I don't always), I just type sagent
.
Here's a pretty nice one that works in Cygwin as well:
SSH_ENV=$HOME/.ssh/environment
function start_agent {
echo "Initialising new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
echo succeeded
chmod 600 ${SSH_ENV}
. ${SSH_ENV} > /dev/null
/usr/bin/ssh-add;
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
. ${SSH_ENV} > /dev/null
#ps ${SSH_AGENT_PID} doesn't work under cywgin
ps -efp ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
Add it to your .bash_profile or .bashrc
Source: http://www.cygwin.com/ml/cygwin/2001-06/msg00537.html