Using ssh-agent for auto login with public keys in Linux

Most of the time when you are using a Desktop Environment in Linux this is already implemented, all you have to do is add AddKeysToAgent yes to your /etc/ssh/ssh_config and you are good to go, the keys will be added to the ssh-agent and can be reused.

In this tutorial we will setup ssh-agent from scratch, but first let’s see how it works.

How ssh-agent works?

The first step is to run the ssh-agent.

eval $(ssh-agent)

We have to use the eval keyword, because the output looks like below and we must set and export the SSH_AUTH_SOCK and SSH_AGENT_PID variables, which will be later used by ssh-add.

SSH_AUTH_SOCK=/tmp/ssh-4Ao0M59fzyhD/agent.12706; export SSH_AUTH_SOCK;
echo Agent pid 12707;

List keys, the output is correct, this means that ssh-add can connect to the ssh-agent socket.
Now you can log into your machines, the keys will be added.

ssh-add -l
The agent has no identities.

If your output looks like below, the variables are not exported correctly, make sure you run ssh-agent using the eval keyword.

Could not open a connection to your authentication agent.


Now that we know how ssh-agent works, it would be easy to add this to your ~/.bashrc file, but it would not be a good choice because you will end up with a lot of ssh-agent services running.

I created a script which will first check if there is a running ssh-agent and make sure that we are not running multiple agents.

running_agent_user=$(pgrep -u $USER ssh-agent | wc -l)
# timeout in seconds, lifetime = 0 (not a good idea if you are using a server)

function start_ssh_agent() {
    echo "Starting ssh-agent"
    ssh-agent -t $timeout_ssh_agent > $tmp_ssh_agent
    chmod 600 $tmp_ssh_agent
    eval $(cat $tmp_ssh_agent)

if [ $running_agent_user == 1  ]
    echo "ssh-agent already running, setting up the environment variables"
    eval $(cat $tmp_ssh_agent)
elif [ $running_agent_user == 0 ]
    echo "ssh-agent is not running"
    echo "Multiple ssh-agent services are running, stopping all the agents"
    kill $(pgrep -u $USER ssh-agent)

Download from GitHub ssh-agent.bashrc

You can setup a timeout value for ssh-agent, I used 3 hours in my script.. feel free to modify it.
The default value for timeout is forever, so your keys will be kept until you restart the ssh-agent or the timeout value expires.

Add the script with the source keyword to your ~/.bashrc or global bashrc found in /etc.

source /path_to_your_script/ssh-agent.bashrc > /dev/null

With this implementation every user will have it’s own ssh-agent, good luck!

Leave a Reply

Your email address will not be published.