How to Add SSH-Keys to SSH-Agent on Startup in MacOS Operating System

Learn How to Add SSH-Key to SSH-Agent on Startup in MacOS

In this article, I am showing an easy solution using which you can add your SSH-Keys in SSH-Agent automatically on startup in macOS.

SSH-Keys are an essential tool for every PHP developer. SSH-Keys are used to connect servers via terminal (command-line tool) without need of entering password every-time. 

SSH-Keys are of two types public and private.

  • Public SSH-Keys: They are not protected with any passphrase and if anyone have those they can get access to your servers.
  • Private SSH-Keys: Whereas private ones need you to enter its passphrase to use them which makes it more secure and most of the people use private keys secure with passphrase.

But if a key is secure with passphrase it will ask you to enter passphrase each time you use it to connect to servers or git repositories. To prevent re-entering passphrase we add SSH-keys to SSH-agent running on your macOS system using the following command:

ssh-add -K ~/.ssh/[your-secure-ssh-key-name]

Above command will ask for passphrase ones. It stores your passphrase in macOS keychain and add SSH-key in SSH-agent, and persist until we restart the system. On restart all keys added in SSH-agents are reset and we need to re-add them. 

Re-adding SSH-keys is kind of an additional task every time you restart, to solve this we need something which automatically adds SSH-keys in SSH-agent and persist them during restarts without asking for passphrase each time. 

In macOS Mojave 10.14.6 (the version I use), we can do that with steps below:

  1. Run the following command in your macOS Terminal app, after running this command it will ask you to enter passphrase for SSK-key and store it in macOS keychain. 
ssh-add -K ~/.ssh/[your-secure-ssh-key-name]

After that, open ~/.ssh/config file in some editor (create on if you don’t find it), then add following in that file:

Host *
  UseKeychain yes
  AddKeysToAgent yes
  IdentityFile ~/.ssh/[your-secure-ssh-key-name]

Now, restart your PC to apply changes properly. Once changes are applied, you will never be asked for passphrase.

After adding your SSK-Keys to SSH-Agent on your system, SSH terminal will directly connect you to server after validating keys between server & SSH-Agent on your system.

Any doubts / questions or suggestions, please add in comments below.

6 Responses

  1. one thing i would add to this is that if you have multiple ssh keys, you should add `IdentityFile /path/to/file` (sometimes full path works more reliably) line for each of you ssh keys. maybe it’s an obvious one, but took me a while.

  2. for OSX 12, “ssh-add –apple-load-keychain ~/ssh/key_ssh” or “ssh-add –apple-use-keychain ~/ssh/key_ssh”

Leave a Reply