Automatic Key Import with ssh-agent/ssh-add

· 3min · Dan F.

If you are like me, then you probably use git as the primary way to manage your code repositories. I also tend to use my own ssh keys to access and manage my repo, so I do not have to remember more passwords. One simple way to manage ssh keys is with the ssh-agent and ssh-add utilities. Things are made easier still be automating the ssh-agent initialization process through bashrc, but this can also lead to complications if one is using a terminal multiplexer.

I used to manage my keys years ago by simply starting a new ssh-agent process via bashrc, and then importing custom ssh key's individually. This process worked well until I started using tmux to manage server-based sessions. Due to the way that bashrc is read with some tmux configurations, every new tmux window or pane caused a new ssh-agent processes to be started, which was not ideal.

There turned out to be a relatively simple solution to this new problem. The ssh-agent utility is able to create a custom socket with which ssh-add is able to communicate with the user's ssh-agent. This action can be used to ensure that only one ssh-agent process is created at any time for a user on a server.

The following simple bash snippet can be inserted in you user's bashrc, along with your specific ssh key name. The basic function of the script is to check if the SSH_AGENT_PID and SSH_AGENT_SOCK variables exist, and if not, start the necessary programs. The end result should be a correctly exported SSH_AGENT_PID and SSH_AGENT_SOCK variables, along with an imported key for use.

This code should be able to work with multiple users on the same server, due to the use of the USER var.

priv_key_name=id_rsa-custom

if [[ -z $SSH_AGENT_PID ]]; then
    if [[ -e /tmp/ssh-agent-$USER ]]; then
        SSH_AGENT_PID=$(ps aux | grep ssh-agent | grep "/tmp/ssh-agent-$USER" | awk '{print $2}')
        if [[ -n $SSH_AGENT_PID ]]; then
            export SSH_AGENT_PID
            export SSH_AUTH_SOCK=/tmp/ssh-agent-$USER
            ssh-add -q $HOME/.ssh/$priv_key
        else
            rm -f /tmp/ssh-agent-$USER
            eval $(ssh-agent -s -a /tmp/ssh-agent-$USER)
            ssh-add -q $HOME/.ssh/$priv_key
        fi
    else
        eval $(ssh-agent -s -a /tmp/ssh-agent-$USER)
        ssh-add -q $HOME/.ssh/$priv_key
    fi
fi

Has been tested on OpenBSD 6.4 and 6.5