Use ssh-agent to Manage SSH Key Passwords on Ubuntu

Managing password-protected SSH keys can become tedious when you have to enter your passphrase every time you connect to a remote server. This guide provides a straightforward tutorial on how to use ssh-agent on Ubuntu Linux to securely store your SSH private key passwords in memory, allowing you to authenticate seamlessly without repeatedly typing your passphrase during your active terminal session.

Step 1: Start the ssh-agent

Before adding your keys, you must ensure that the ssh-agent is running in the background of your current terminal session. Run the following command to start the agent:

eval "$(ssh-agent -s)"

This command starts the agent process and registers the necessary environment variables in your current shell.

Step 2: Add Your SSH Private Key to the Agent

Once the agent is running, you can add your private key. By default, SSH keys are stored in the ~/.ssh directory. Run the ssh-add command followed by the path to your private key:

ssh-add ~/.ssh/id_rsa

Note: If your key uses a different encryption algorithm (such as id_ed25519), replace id_rsa with your actual file name.

You will be prompted to enter your private key’s passphrase. Once entered successfully, the agent will cache the key in memory, and you will not have to enter the passphrase again for this session.

Step 3: Verify the Cached Keys

To confirm that your private key has been successfully loaded into the agent, you can list the active keys using the following command:

ssh-add -l

This command will output the key size, fingerprint, and file path of all identities currently managed by the active agent. You can now SSH into your remote servers without being prompted for a passphrase.

Step 4: Automate ssh-agent on Login (Optional)

While Ubuntu desktop environments often handle SSH key management automatically via the GNOME Keyring, you may want to automate this process in a standard bash shell (especially on Ubuntu Server).

To automatically start ssh-agent and add your key whenever you open a new terminal, open your ~/.bashrc file:

nano ~/.bashrc

Add the following lines to the bottom of the file:

if [ -z "$SSH_AUTH_SOCK" ] ; then
  eval "$(ssh-agent -s)"
  ssh-add ~/.ssh/id_rsa
fi

Save and close the file (press Ctrl+O, Enter, then Ctrl+X in Nano). To apply the changes immediately, run:

source ~/.bashrc