How To Manage Multiple SSH Keys

Amogh | Sep 12, 2023

In the previous article you learnt how to connect between two Linux machines, in this tutorial, you are going to learn how to manage more than one ssh keypair effectively.

In your .ssh directory, create a file called config. Inside the config add the following lines:

Host Cat
  HostName cat.com
  User amoghavarsha
  IdentityFile ~/.ssh/id_rsa
  IdentitiesOnly yes

Host Dog
  HostName dog.com
  User amoghavarsha
  IdentityFile ~/.ssh/id_rsa.1
  IdentitiesOnly yes

Host *
  AddKeysToAgent yes
  IdentityFile ~/.ssh/id_rsa
  IdentityFile ~/.ssh/id_rsa.1

Imagine we have two hosts i.e., Cat and Dog. Their hostnames are cat.com and dog.com, respectively. And we have created two separate ssh keypairs for cat.com and dog.com. As you can see in the IdentityFile, cat.com’s private key is id_rsa and dog.com’s private key is id_rsa.1. You can name your public and private keys however you want.

For example, you can generate an ssh keypair for cat.com and name its public key as the cat.pub and private key as cat. Likewise, you can create an ssh keypair for dog.com and name its public key as dog.pub and private key as dog.

Follow the above procedure if you have more than 2 ssh keypairs. Technically, you can have as many ssh keypairs you wish to have. Also add as many _IdentityFile_s under AddKeysToAgent, depending on number of keypairs you have.

So, if you are familiar with my last article, you’ll know how to connect to a remote computer. But what if you have multiple keypairs and you want to connect to a specific server or computer?

It’s pretty simple to do that. Just type the following command:

ssh -i ~/.ssh/id_rsa Cat

or

ssh -i ~/.ssh/id_rsa [email protected]

or

ssh -i ~/.ssh/id_rsa username@<IP address of cat.com>

As you can see from the above code block, by using the -i flag and specifying the location (~/.ssh/id_rsa) of your private key to cat.com and followed by Host or full address, you can connect to the remote server.

And also, you can name your Host with whatever name you want. Rather than tying the whole address, having a short Host(Host Cat) name could come in handy.

You can follow me on other social media.