A unique problem arises when my personal laptop left this world and even after lots of software and hardware fixes, I was unable to fix it. Now I was left with my office laptop and sorrow.
So basically my personal github account had my personal laptop's ssh key and work's github account had my office's laptop's ssh key. Now I needed to access my personal github account with my office's laptop. But but but..... you can add one ssh key in one github account only. So what to do now? How can I manage both the accounts with same laptop.
There's a very easy and interesting solution to this problem. I will explain it step by step.
Add a new ssh key pair to your office's laptop
ssh-keygen -t rsa -f ~/.ssh/id_rsa.home ssh-keygen -t rsa -f ~/.ssh/id_rsa.office
This will generate two ssh key pairs with different names for identifying keys to be used for personal github account and official account.
Okay, now how to configure which key to use for which account?
Now is the time to edit ssh config file so that it can pick ssh key according to the server it connects to
# Personal GitHub account: Host home-github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa.home PreferredAuthentications publickey PasswordAuthentication no IdentitiesOnly yes # Work GitHub account: Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa.office PreferredAuthentications publickey PasswordAuthentication no IdentitiesOnly yes
Lines starting from "#" are considered as comments as usual. And then few key value pairs of hostname, user, file to be used for ssh and few extra settings.
There's a catch also. While adding remote url in local repo we have to modify the url according to the hostname we provided in the config file. So for e.g my remote url is
which is my perosnal github account this will become
But what about github username while commit??
This we can handle by adding some alias for changing git config so that commit will have user email id according to account type(official and personal)
#git alias alias gitmeHome='git config user.email firstname.lastname@example.org' alias gitmeWork='git config user.email email@example.com'
And voila! every time you need to switch realms just call this alias and you are ready to rule that one.
- I only demonstrated this for two git accounts but this can be applied to differentiate any two server or any number of servers. In fact for each we should have different ssh key so that even if one gets compromised we still have other safe.
- For changing git config file we can change username also if that is necessary.
- I am writing blog almost after more than 1 year, so pardon me for my mistakes.
I hope I clearly explained this topic, if you have any doubts please write in the comments below.
Blog reviewed by - Deepika Verma