8

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?

7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.