ssh agent across multiple hosts

I would like secure single-sign-in across multiple hosts. An easy way to do this is with ssh-agent, however, ssh-agent is a bit limited.

For example, the normal use of ssh-agent looks like this,

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-stSwW11394/agent.11394; export SSH_AUTH_SOCK;
echo Agent pid 11395;

You would need to set those environment variables to use the newly created agent, and then use ssh-add to add your credentials, e.g.,

$ eval `ssh-agent`
Agent pid 11464
$ ssh-add
Enter passphrase for /home/foobar/.ssh/id_dsa: 
Identity added: /home/twarnock/.ssh/id_dsa (/home/foobar/.ssh/id_dsa)
$ ssh-add -l
1024 84:e3:23:7b:f4:22:a2:da:53:fb:04:19:67:78:2b:3d /home/foobar/.ssh/id_dsa (DSA)

From here you can access any hosts that has your public key in ~/.ssh/authorized_keys

However, any new shell instances on this same host would have to go through this process. Ideally, I want to login ONCE and ONLY ONCE while working across multiple hosts.

The following code snippet can be added to your .bashrc which maintains a single agent across multiple shells per host, and also respects ssh auth forwarding. This code will also work in situations where your home directory is mounted across multiple hosts (maintaining an ssh-agent per host as needed, depending on where you login first).

# ssh agent -- for shared home directory across hosts
function start_agent {
  echo "Starting a new ssh-agent on this host"
  ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
  chmod 600 ${SSH_ENV}
  . ${SSH_ENV} > /dev/null
  echo succeeded

## ssh-agent
if [ -e "$SSH_AUTH_SOCK" ]; then
  echo "Using ${SSH_AUTH_SOCK}"
elif [ -f "${SSH_ENV}" ]; then
  echo "Using ${SSH_ENV}"
  . ${SSH_ENV} > /dev/null
  ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    echo "${SSH_ENV} agent is no longer running"

With this scenario you typically need to only login once per work session (regardless of which host you first login to). And with appropriate use of ssh auth forwarding, e.g., ssh -A user@host, you can jump around from host-to-host without constantly typing in the same password.

This entry was posted in shell tips, ssh. Bookmark the permalink.

Comments are closed.