Use of SSH keys to access multiple servers

SSH keys is a miracle and it eases all the authentication troubles that we faced in connecting server, uploading files and accessing console when dealing with multiple hosts. On the other hand, SSH keys will be a pain in the ass unless we know how to use them properly, when, how and why? This post will list the usages of the SSH keys in some development and deployment environments I am working with.

Access Digital Ocean droplet

The droplet already provides a web-based console to access your droplet. But it does not feel direct-remote to me but remote-remote access. So, let's find out how to access from our Terminal in Mac.

Server info and Login Credentials

Before we begin, we need to note down our the following.
1. User name: the remote user to log in (it is root* if you haven't changed)
2. **A pair of SSH keys
: the public key to add your droplet and the private key to authenticate (and passphrase if you set one).
3. Droplet's IP: Assigned by the Digital Ocean to address your droplet.

If you don't have a SSH key to continue, you can take a look at How to use SSH Keys in Mac OS X.

Add the SSH key to a new droplet

  1. In Terminal, pbcopy < ~/.ssh/id_rsa.pub to copy the your generated SSH public key.
  2. Go to Settings => Security in your Digital Ocean account and Click Add SSH key.
  3. Paste in the SSH key context text area and Type a Name like your computer name or whatever identity to yourself.
  4. And when you create a new droplet, this SSH key will be automatically added.

Add the SSH key to the existing one

On OSX, the action is taken by only one command
cat ~/.ssh/id_rsa.pub | ssh root@123.45.56.78 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

If you had not changed your default root password of your droplet, you will need to change unless it wont let you execute this command.

On linux, it has never been easier...

ssh-copy-id root@123.45.56.78

Configuration ssh for multiple host

It is very unlikely that we all have only one server to enable access with SSH. You have to memorise username and host address for each server. But a simple config file inside the ssh folder can make your life easy.

  1. Type cd ~./ssh in your Terminal and create a new file named config with touch config command.
  2. Edit our newly created config file, with whatever editor you like, nano config in my case.
  3. Type the following configuration for each of your server, and Save.
Host Server1  
 HostName 123.45.56.78
 User root
 IdentityFile ~/.ssh/id_rsa

Host Server2  
 HostName 123.45.56.79
 User root
 IdentityFile ~/.ssh/id_rsa

4 Finally, type ssh-add in Terminal.

That's it, we can successfully login to our droplet with SSH.

A lot of thanks to my colleague, Du Wun Aung for helping me out with this post.

Nay Win Myint

Founder and CEO of Pancasikha Music Streaming Provider, JavaScript full-stack and Android developer and Graphic designer.

Rangoon, Myanmar