Using SSH agent on Ubuntu server

When working with private keys that are protected with a passphrase on Ubuntu server you will be prompted you to enter the passphrase on each use. Just like on your desktop environment you can however use an SSH agent in which you load your keys for the duration of your session.

To use the SSH agent you need to start it using the following command:

cor@wolf:~$ eval $(ssh-agent)
Agent pid 1350378

ssh-agent forks itself in the background and outputs instructions to update your shell environment, if you run the same command without eval it looks something like this:

cor@wolf:~$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-rZb7gcHVILgN/agent.1350488; export SSH_AUTH_SOCK;
SSH_AGENT_PID=1350489; export SSH_AGENT_PID;
echo Agent pid 1350489;

If you do not use eval with the initial command you would have to execute the output manually, otherwise you will not be able to use the ssh-agent that is running in the background.

To load private keys into ssh-agent you use the ssh-add command:

cor@wolf:~$ ssh-add
Enter passphrase for /home/cor/.ssh/id_ecdsa:
Identity added: /home/cor/.ssh/id_ecdsa (cor@wolf)

It will look for a number of default key file names in your ~/.ssh directory, if you want load another key you can specify it as an argument to this command.

Once your key is loaded into ssh-agent other SSH commands will now use it from ssh-agent and you will not be prompted for the passphrase again. From this point on you can even start a tmux session and use the same ssh-agent in there.

For security’s sake you should terminate the ssh-agent once you end your session (just like you wouldn’t leave your car unlocked with the keys in the ignition and then walk away either). To terminate the ssh-agent use following command:

cor@wolf:~$ eval $(ssh-agent -k)
Agent pid 1350627 killed

This command kills the ssh-agent referenced in your environment variables and outputs instructions to update your environment, if you would run this command without eval it would look like this:

cor@wolf:~$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 1350883 killed;

Not updating the environment may cause unexpected errors, for example ssh-add will return an error as it cannot connect the (no longer running) ssh-agent:

cor@wolf:~$ ssh-add
Could not open a connection to your authentication agent.