Configure ssh-agent on Linux

linux
Published

October 2, 2024

I keep Googling this again and again.

First, ssh-agent does not need to run on the remote server, it is the local agent which is forwarded over ssh to the remote server.

On the local machine, configure ssh-agent so that it starts only once, credit to this gist, add this to .bashrc:

# SSH agent
ssh_pid_file="$HOME/.config/ssh-agent.pid"
SSH_AUTH_SOCK="$HOME/.config/ssh-agent.sock"
if [ -z "$SSH_AGENT_PID" ]
then
    # no PID exported, try to get it from pidfile
    SSH_AGENT_PID=$(cat "$ssh_pid_file")
fi

if ! kill -0 $SSH_AGENT_PID &> /dev/null
then
    # the agent is not running, start it
    rm "$SSH_AUTH_SOCK" &> /dev/null
    >&2 echo "Starting SSH agent, since it's not running; this can take a moment"
    eval "$(ssh-agent -s -a "$SSH_AUTH_SOCK")"
    echo "$SSH_AGENT_PID" > "$ssh_pid_file"
    ssh-add -A 2>/dev/null

    >&2 echo "Started ssh-agent with '$SSH_AUTH_SOCK'"
# else
#   >&2 echo "ssh-agent on '$SSH_AUTH_SOCK' ($SSH_AGENT_PID)"
fi
export SSH_AGENT_PID
export SSH_AUTH_SOCK

If ssh-agent ever gets stuck:

rm $HOME/.config/ssh-agent*

In case we want to load ssh keys at login, add also this to .bashrc (do just ssh-add to add all keys under .ssh):

if ! ssh-add -l &>/dev/null; then
      echo Adding keys...
      ssh-add ~/.ssh/id_rsa
fi

Finally, we can configure automatic forwarding to some of our SSH remote servers in .ssh/config:

Host myserver
    HostName myserver.mydomain.com
    User myusername
    ForwardAgent yes

Now login to the remote server and check keys are properly forwarded running:

ssh-add -L