Even if we’ve set a passwordless ssh login environment using private and public keys, we still need to type in the passphrase for the private key when logging into the remote server via SSH.

The passphrase only needs to be typed in once for the ssh-agent running in a terminal session. However, if the session is terminated, the private key should be added to the ssh-agent again, for which we need the passphrase.

To resolve the issue, this article introduces how to permanently add the passphrase to an ssh-agent. For macOS, the passphrase would not be needed even after rebooting a machine. For ubuntu, we only have to type in the passphrase once after rebooting a machine.

For macOS

Adding private key to macOS keychain

Open up a terminal and type the following to add the private key to the keychain application:

$ssh-add --apple-use-keychain ~/.ssh/id_rsa  • Info. • The above command is validated in macOS Monterey 12.4. • If it’s not working, try ssh-add -K ~/.ssh/id_rsa. Let ssh-agent always use macOS keychain Configure .ssh/config as follows: Host * UseKeychain yes AddKeysToAgent yes IdentityFile ~/.ssh/id_rsa  Note: .ssh/config should be with permission 644. For Ubuntu Install keychain Install the keychain using the following command: $ sudo apt-get install keychain


Keychain checks for running ssh-agent (or starts one) and let the agent to hold the private key. It also saves the agent’s environment for which ssh login attempts to reference the environment for passwordless ssh connections.

Let keychain hold private key

Open .zprofile (or .bash_profile) and type the following to save the private key to the installed keychain.

...
if [[ uname == Linux ]] then
/usr/bin/keychain $HOME/.ssh/id_rsa source$HOME/.keychain/\$HOST-sh
fi
...


Info. Adding the above in .zshrc or .bashrc also works.

Let ssh-agent always use keychain

Configure .ssh/config as follows:

Host *
IgnoreUnknown UseKeychain
UseKeychain yes
IdentityFile ~/.ssh/id_rsa


Info. We actually need only the IdentityFile property. But for the compatibility of the config file with the macOS, we just prepend the IgnoreUnknown UseKeychain property, which prevents error using the UseKeychain property not defined for Ubuntu.

Tags:

Categories:

Updated: