6

In Ubuntu 16.04 I executed:

eval $(ssh-agent) && ssh-add

I got:

Agent pid 3361

I then SSH tunneled into my VPS successfully, after inserting my passphrase.

The problem:

Well, it's not that much of a "problem", but:

I went back to my local session with exit, and when I tried to login to my VPS again, I had to reenter my passphrase...

My question:

Why would I be asked to enter the passphrase again?

I didn't close the current session and did eval $(ssh-agent) && ssh-add, before tunneling. So, why the system won't "remember" it?

2 Answers2

3

Every time you do eval $(ssh-agent) && ssh-add, a new agent starts, so you need to re-authenticate yourself to it.

I think the best way is to store the SSH agent data permanently per session (in your ~/.profile):

export SSHPROC=${HOME}/.ssh/cur-proc.${HOSTNAME}
restart_ssh_agent(){
  . ${SSHPROC}
  kill ${SSH_AGENT_PID}
  /bin/rm -rf ${SSHPROC} ${SSH_AUTH_SOCK} /tmp/ssh-*
  ssh-agent > ${SSHPROC}
  cat ${SSHPROC}
  . ${SSHPROC}
  ssh-add
}

and add . ${SSHPROC} to your .bashrc.

Then you call restart_ssh_agent once (or when it dies for some reason) and then keep your credentials with the agent.

sds
  • 2,643
2

You need to detect if ssh-agent is already running via your .bashrc. If it is not running, then start it. If it is already running, then use it.

Here's a snippet from my .bashrc which sets up environment variables for an existing session.

#
# setup ssh-agent
#
#start running ssh-agent if it is not already.
if [ ! 'root' = "${USER}" ]; then
  if ! pgrep ssh-agent &> /dev/null && ! uname -rms | grep Darwin &> /dev/null; then
    eval "$(ssh-agent -t 3600)" > /dev/null
  fi
  if ! uname -rms | grep Darwin &> /dev/null; then
    if [ -z "${SSH_AUTH_SOCK}" -o -z "${SSH_AGENT_PID}" ]; then
        #first time failed so try again.
        SSH_AUTH_SOCK="$(ls -l /tmp/ssh-*/agent.* 2> /dev/null | grep "${USER}" | awk '{print $9}' | tail -n1)"
        SSH_AGENT_PID="$(echo ${SSH_AUTH_SOCK} | cut -d. -f2)"
    fi
    if [ -z "${SSH_AUTH_SOCK}" -o -z "${SSH_AGENT_PID}" ]; then
      SSH_AUTH_SOCK="$(lsof -p "$(pgrep ssh-agent | tr '\n' ',')" | grep "${USER}" | grep -e "ssh-[^/]*/agent\.[0-9]\+$" | tr ' ' '\n' | tail -n1)"
      SSH_AGENT_PID="$(echo ${SSH_AUTH_SOCK} | cut -d. -f2)"
    fi
  fi
  [ -n "${SSH_AUTH_SOCK}" ] && export SSH_AUTH_SOCK
  [ -n "${SSH_AGENT_PID}" ] && export SSH_AGENT_PID
fi

I use that same snippet for multiple platforms and not just Mac or Linux on x86. That snippet can be further improved but for now it works for me reliably.