SSH – How to Get Asked for SSH Key Passphrase Once and Only When Needed

sshssh-agent

(I have read many of the questions on this site that look related and I believe this is a genuinely new question.)

I have lots of keys on lots of servers and they're all protected with passphrases.

I like entering passphrases about as much as I like entering passwords – it's a real productivity drain.

  • ssh-agent + ssh-add commands can be used on a login shell to mean you only have to enter your passphrase once at login

  • keychain can be used to hold an ssh-agent alive beyond logout, so for example you can have it so you only have to enter the passphrase once at boot, or you can have it keep it alive for an hour or so.

The problem I have is that both of these solutions typically get initiated in a shell login (e.g. .zshrc) rely on me entering my passphrase when I log in, even if I'm not going to need it unlocked. (I'm not happy with keychain keeping an agent alive indefinitely.)

What I would like is to be prompted for a passphrase (for an agent) only when needed.

So I can log in to server A, do some stuff, then ssh to server B and at that point be asked for the passphrase. Do some stuff on server B, log out. Back on A, do some more stuff, ssh to B again and not need my passphrase (it's held by an agent).

I note that this is possible on graphical desktops like Gnome – you get a pop-up asking for the passphrase to unlock your private key as soon as you try to ssh. So this is what I'm after but from a console.

Best Answer

Don't add anything to any of your shell startup scripts, this is unnecessary hackery.

Instead, add

AddKeysToAgent yes

to your .ssh/config

Like this, ssh-add is run automatically the first time you ssh into another box. You only have to re-enter your key when it expires from ssh-agent or after you reboot.

Related Question