Multiple SSH keys for github

Posted on Sun, May 24, 2020 Git web

In case you ever need 2 accounts on Github, there's a way to register multiple SSH keys so that you will always commit to the chosen repo using the appropriate account. This post was written because I had to combine methods from a few folks.

I'm writing this guide for Windows but the concept also applies to Linux, minus some syntax. Make sure you have Git â‰Ĩ 2.13

Step 1: Generate SSH keys

Open up git-bash. Let's say you have a main account with an existing SSH key, your ~/.ssh folder should have the following:

$ ~/.ssh/id_rsa
$ ~/.ssh/id_rsa.pub

You can delete → remake them with another name to differentiate between account#1, #2, etc... Leaving them the same is fine too, but for the purpose of this post, I'll rename them to something else

Generate your 2nd SSH key:

ssh-keygen -t rsa -C "personal@email.com"

Rename it to something else when prompted. You should now have the following

$ ~/.ssh/id_rsa_work
$ ~/.ssh/id_rsa_work.pub
$ ~/.ssh/id_rsa_personal
$ ~/.ssh/id_rsa_personal.pub

Step 2: Generate/Edit config file:

This config file is there to differentiate between different accounts since Git â‰Ĩ 2.13. Let's generate and/or edit it:

cd ~/.ssh
touch config
nano config

Put this into your config:

#Your existing/1st account:
Host work.github.com
	HostName github.com
	PreferredAuthentications publickey
	IdentityFile ~/.ssh/id_rsa_work

#2nd account
Host me.github.com
	HostName github.com
	PreferredAuthentications publickey
	IdentityFile ~/.ssh/id_rsa_personal

The 2 main lines you need to pay attention to are the 1st and 4th line of each block.

Step 3: Set the remote origin of the repo(s) according to your account

If the SSH link to your repo is git@github.com:USERNAME/REPO.git

To use the 1st account:

git remote set-url origin git@work.github.com:USERNAME/REPO.git

To use the 2nd account

git remote set-url origin git@personal.github.com:USERNAME/REPO.git

If the command returns a no origin error, remember to add origin first!

Step 4: User details:

Let's change dirs to your appropriate repo and set git config user details since you want to distinguish your accounts

cd ~/personal_repo
git config user.name "personal_user"
git config user.email "personal@email.com"

And... we should be done! The most important thing to remember is to set your working repos to match with your Host in the configfile.

Source(s):

https://coderwall.com/p/7smjkq/multiple-ssh-keys-for-different-accounts-on-github-or-gitlab

https://gist.github.com/jexchan/2351996

https://medium.com/@trionkidnapper/ssh-keys-with-multiple-github-accounts-c67db56f191e