14

I want to use keychain to manage passphrase prompt for SSH keys, but it should 1) ask it only when I'm actually using key and 2) save it for some period of time after that. Currently I've 2 options:

  1. $ eval `keychain --eval --agents ssh id_rsa` -- that will always ask for passphrase at start up but then it will save it.
  2. $ eval `keychain --eval --noask --agents ssh id_rsa` -- that won't ask for anything on start up but then will keep asking for passphrase each time I will use that key.

Is there are any way to combine advantages of these methods?

Jakuje
  • 21,357
anlar
  • 4,165
  • Funny thing is, when I take the second approach, I'm not asked for a passphrase even when I try to ssh. I wonder why that is. – amzon-ex Nov 04 '22 at 05:44

1 Answers1

14

The ssh-agent and recent versions of OpenSSH make it simple:

  1. Start normal ssh-agent with default timeout for the keys added (60 minutes for example):

    eval `ssh-agent -t 60m`
    
  2. Configure your ssh to add actually used keys to the agent. Add a new line to ~/.ssh/config`:

    AddKeysToAgent yes
    

    This feature is in latest OpenSSH 7.2. In the previous versions, you need to add the key to the agent manually, if your timeout is exceeded, but it can be quite simply automated using bash function, something like this:

    ssh() {
      /bin/ssh -o BatchMode=yes $* || \
        ssh-add path/to/the-key && /bin/ssh $*
    }
    

    The idea: Try to connect using the key in batch-mode (will not prompt for passphrase and fail, if the key is not there) and upon failure, add the key to the agent and re-run the ssh command.

Jakuje
  • 21,357