Manage Multiple SSH Keys in the Same Machine

Imagine a situation that you are not allowed to use your GitHub SSH key to access a GitLab account that is shared under a collaborative project. To resolve this problem, we may simply create another SSH key for the access to the GitLab account. Here is a short tutorial for the management of multiple SSH keys in the same machine.

Prerequisites

I assume you have had a GitHub account and a GitLab account but have not created any SSH keys for the access to either of the Git repositories. Then, let’s do some sanity check for our toy project: in a directory that doesn’t contain any Git repositories, check the global setting of Git:

$ git config --list

Configure the global setting of user name and user email for your GitHub account (you may choose the GitLab account as well. Just be mindful to make corresponding modification when we walk through the rest of the tutorial):

$ git config --global user.name  # your GitHub user name
$ git config --global user.email # your email account

Generate GitHub SSH key

Simply run:

$ cd ~/.ssh
$ ssh-keygen -t rsa -C "Your-Email-Address-for-GitHub" -b 4096

You would be prompted to give the public key a name. We may just call it id_rsa_github. There is no file extension needed for your answer.

Refer to the article Why use -t rsa -b 4096 with ssh-keygen? for details.

Then, we can retrieve the public key by running:

$ cat id_rsa_github.pub

Copy and paste it to the SSH and GPG Keys webpage of GitHub.

Generate GitLab SSH key

Similarly, we generate another SSH key for GitLab.

$ ssh-keygen -t rsa -C "Your-Email-Address-for-GitLab" -b 4096

The email account could be the same. It doesn’t matter. But be sure to save it as id_rsa_gitlab, for example, so as to differentiate itself from the GitHub SSH key we made early.

In the end, copy and paste the newly generated public SSH key to the SSH keys webpage in GitLab.

Add SSH keys to SSH Agent

$ ssh-add ~/.ssh/id_rsa_github
$ ssh-add ~/.ssh/id_rsa_gitlab

If you encounter the error message similar to that shown below

Could not open a connection to your authentication agent

Try to solve this problem by running:

$ ssh-agent bash

And then repeat the ssh-add command for each private SSH key.

The last step is to navigate to ~/.ssh and edit the file config by adding:

Host github.com  
    HostName github.com  
    PreferredAuthentications publickey  
    IdentityFile ~/.ssh/id_rsa_github  

Host gitlab  
    HostName gitlab 
    PreferredAuthentications publickey  
    IdentityFile ~/.ssh/id_rsa_gitlab

You may check if the connection works:

$ ssh -T git@github.com
$ ssh -T git@gitlab.com

If welcome message is shown, you have two SSH keys in the same machine now.

References

[1] github账号与gitlab同一电脑下不同SSH Key配置