How to avoid macOS for keep asking for the passphrase for key ~/.ssh/id_rsa while remotely operating via ssh?

Solution 1:

You need to use ssh-agent to manage your passphrase.

This assumes you have already generated SSH keys to log into your host(s). If not, see How to SSH in one line for a primer on how to do this.

Next add your key to the agent

ssh-add

If it requires a passphrase, it will ask for it. Now, every time you SSH to your remote Mac, it won't ask you for the passphrase until you kill the (local) Terminal session. If you start a new one, it will ask once then remember it for the duration of that Terminal session.

Can you get around having to enter a passphrase at all? Yes...

  • Don't put one in. It's asking because you created a key file with a passphrase.

  • hard code it into a script (not advisable)

As for going from one Mac, to another and finally out to another server (i.e. GitHub), you will need to enable (set to "yes") ForwardAgent in both your ssh_config and sshd_config. See this article for more info.

Solution 2:

First, Allan is right to enter "UseKeychain yes" in your .ssh/config file. Second, my method comes also handy in another way

# Use Apple Keychain for ssh-key passphrases
UseKeychain yes
# automatically load keys into ssh-agent
AddKeysToAgent yes
# Automatically forward ssh-agent to destination
ForwardAgent yes

If you know add the key to your ssh-agent by issueing

ssh-add <keyfile>

and enter your passphrase, you can start. BUT you also add your passphrase to you keychain:

ssh-add --help
...
  -K          Store passphrases in your keychain.
          With -d, remove passphrases from your keychain.

So with

ssh-add -K <keyfile>

you not only load your key but also save the passphrase in your keychain. You have to issue the "-K" only once.

With that configuration you have a save key and the passphrase safely stored in your keychain and whenever you open a terminal using ssh, the key is automatically loaded into you ssh-agent and the passphrase is taken from your keychain.