SSH keys should be your standard, go-to for interacting with any remote server. They remove the need to memorize a server password. They allow you to login programmatically, and they give your local operating system the chance to handle the caching of your password in your keychain. It’s also very simple.
A few rules you should always follow.
- Always make a passphrase.
- Don’t use the same SSH key on multiple important servers.
- Don’t share the private key. All commands here are ran in a BASH or equivalent (common equivalents are the ‘Terminal’ program in most POSIX OS).
This creates a public/private key pair. The public key is shared with whatever server or service you want to log into securely.
ssh-keygen kicks up a series of questions. You should always make a passphrase. If your private key does happen to be stolen, the passphrase will slow down the chances of using the key. Most operating systems will cache the key locally when it’s used the first time in your user keychain. This keeps you from having to enter it in every single time. Sometimes, a keychain isn’t set up for this. Luckily you can use
ssh-agent to cache your passphrase, combined with
ssh-add (more on this later).
Next, you need a way to send your public key to a server. The easy way is to use the
**ssh-copy-id** tool. If you are using OSX, then I recommend getting Homebrew.
brew install ssh-copy-id
Now you can use
The NAME is your username on the server and SERVER is the hostname or I.P. of the server. It will then ask for you to enter your password. Once this is done, your public key will be available at _SERVER:~NAME/.ssh/authorized_keys_. Many times, services like GitHub and BitBucket will request that you simply copy the contents and paste the public key to the website. I usually just use
**cat ~/.ssh/KEYNAME** and then copy it from the terminal in those cases. KEYNAME is the name you gave the key during
**ssh-keygen** (default is id_rsa).
Now, when you connect (
**ssh NAME@SERVER**) to the SERVER you were wanting to login to, it should only ask you for the pass-phrase entered during
**ssh-keygen**. If you have entered it recently, your keychain should have cached it and you won’t have to enter it again. Sometimes there is no keychain. For this you will want to run
**ssh-agent** and then
**ssh-add ~/.ssh/KEYNAME**, which will then ask for your passphrase. For
**ssh-agent**, you do want to run via
exec ssh-agent $SHELL && ssh-add ~/.ssh/KEYNAME
**ssh-agent** is not directly available. For this, I’ve found
**exec /usr/bin/ssh-agent $SHELL** works just as well (assuming /usr/bin is where your OS keeps
**ssh-agent**; CentOS in particular).
exec /usr/bin/ssh-agent $SHELL && ssh-add ~/.ssh/KEYNAME
And now, you should be able to connect to a server, more securely than a password while not needing to pass around passwords!