Problem
I have two Github accounts: oanhnn (personal) and superman (for work). I want to use both accounts on same computer (without typing password everytime, when doing git push or pull).
Solution
Use ssh keys and define host aliases in ssh config file (each alias for an account).
How to?
-
Generate ssh key pairs for accounts and add them to GitHub accounts.
-
Edit/Create ssh config file (
~/.ssh/config
):# Default github account: oanhnn Host github.com HostName github.com IdentityFile ~/.ssh/oanhnn_private_key IdentitiesOnly yes # Other github account: superman Host github-superman HostName github.com IdentityFile ~/.ssh/superman_private_key IdentitiesOnly yes
-
Add ssh private keys to your agent:
$ ssh-add ~/.ssh/oanhnn_private_key $ ssh-add ~/.ssh/superman_private_key
-
Test your connection
$ ssh -T git@github.com $ ssh -T git@github-superman
With each command, you may see this kind of warning, type
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:
Hi oanhnn! You've successfully authenticated, but GitHub does not provide shell access.
Hi superman! You've successfully authenticated, but GitHub does not provide shell access.
-
Now all are set, just clone your repositories
$ git clone git@github-superman:org2/project2.git /path/to/project2 $ cd /path/to/project2 $ git config user.email "superman@org2.com" $ git config user.name "Super Man"
Done! Goodluck!
Thanks so much. This was very helpful. A little thing you need to add in step 5 if the repo was not cloned:
git config core.sshCommand "ssh -i ~/.ssh/superman_private_key -F /dev/null"
This will let you use the
superman_private_key
file every time you fetch, pull, or push to the remote from project2 local repo.Alternatively, if the repo was created locally (i.e. not cloned), setting the remote with the alias will also do that:
git remote add origin git@github-superman:org2/project2.git