How to make ssh-agent automatically add the key on demand?

ssh supports adding a key to the agent on first use (since version 7.2).  You can enable that feature by putting the following into ~/.ssh/config:

AddKeysToAgent yes

This also works when using derivative tools, such as git.

From the 7.2 changelog:

  • ssh(1): Add an AddKeysToAgent client option which can be set to 'yes', 'no', 'ask', or 'confirm', and defaults to 'no'.  When enabled, a private key that is used during authentication will be added to ssh-agent if it is running (with confirmation enabled if set to 'confirm').

You could cheat and put something like alias ssh='ssh-add -l || ssh-add && ssh' on your .bashrc / .profile. This first runs ssh-add -l, which can return 0 (there are keys on agent), 1 (no keys) or 2 (no agent running); if it returns 0, ssh will run; if 1, ssh-add will run and then ssh; if 2, ssh-add will fail and ssh won't be run. Replace the && with ; if you want ssh to run even when there's no agent running.


Until auto-call-ssh-add is supported by ssh, I added this in my .bashrc, based on Kovensky proposal:

ssh-add -l >/dev/null || alias ssh='ssh-add -l >/dev/null || ssh-add && unalias ssh; ssh'

The alias is created only if the identity is not added, and the alias destroys itself once run.

This way the regular ssh command is used after the identity has been added.

Tags:

Ssh

Ssh Agent