Multiple Git accounts – ssh authentication

Multiple Git accounts on your Mac/Window

File:Git-logo.svg - Wikimedia Commons
git

Problem statement

Multiple Git ssh accounts – You are working under your business GitHub account. At the same time, you’d like to work on a personal/side project using your personal GitHub account.

Solution

Using multiple configurations inside your config file under your /.ssh folder. I’m using Github as an example.

Step by step

Generating ssh key pairs

Generate ssh key pairs for accounts 

Add public keys into your Github account

add them to GitHub accounts.

Update/Generate ssh config file (~/.ssh/config):

#Default business Github account: khanh-business
Host github.com
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa

#Personal Github: khanh-personal
Host github.com-personal
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa_personal

Add ssh private keys to your ssh agent

Add ssh private keys to your agent:

$ ssh-add ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa_personal

Test the connections of the ssh keys

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

You may see this warning message regarding authenticity of host, go ahead with yes

The authenticity of host 'github.com (192.30.252.1)' can't be established.
RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:
Are you sure you want to continue connecting (yes/no)?

If everything is OK, you will see these messages regarding successfully authenticated with Github

Hi khanh-business! You've successfully authenticated, but GitHub does not provide shell access.
Hi khanh-personal! You've successfully authenticated, but GitHub does not provide shell access.

Now all done, clone your repositories using multiple GitHub ssh accounts

$ git clone git@github.com-personal:username/your-repo.git /path/to/repo
$ cd /path/to/repo
$ git config user.email "youremail@domain.com"
$ git config user.name  "your name"

To push to commits/changes to the remote URL

$ git remote set-url origin https://<your_username>:<git_access_token>@github.com/<your_username>/<repo>.git
$ git push --set-upstream origin master

See how to get your personal access token https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token

Kudos to the original author: oanhnn

Leave a Reply