How to work with multiple ssh keys

Arun Rana picture Arun Rana · Jan 19, 2012 · Viewed 24.1k times · Source

GitHub Users,

I am newbie on github and have some issue with git setup. I have 2 account with different users on github and i have setup git on my system 2 times

First /.ssh folder (as usual) (contain id_rsa which copied in first account)
Second /.ssh/new folder (contain id_rsa which copied in second account)

now at the time of push how can i switch between ssh key?

Because if i would like to push for second account it will use .ssh key instead of .ssh/new and gives me error.

Please make me correct if i am understood something wrong here.

Thanks.

Answer

Mark Longair picture Mark Longair · Jan 19, 2012

(I've voted to close this as a possible duplicate, but I might as well add a similar answer anyway.)

When using the SSH transport, GitHub identifies you as a user based on the SSH key that you use to authenticate. So, you need to make sure that git is using one SSH key for one repository and another for the other.

I'm going to assume that:

  1. You have a GitHub account called user1, and you've added to that account the public key corresponding to your local private key /home/whoever/.ssh/id_rsa. Let's say that the repository you're interested in accessing as user1 is user1/whatever on GitHub.
  2. You have a second GitHub account called user2 and you've added to that account the public key corresponding to your local private key /home/whoever/.ssh/new/id_rsa. Let's say that the repository you're interested in accessing as user2 is user2/whatever on GitHub.

The simplest way to do deal with this is to create a new "remote" (i.e. a nickname for a remote repository) for each repository, where the hostname is in each remote's URL is actually an alias that you've set up in ~/.ssh/config. (If that config file doesn't exist, you'll have to create it.)

For example, one entry in the ~/.ssh/config file might look like:

Host github-as-user1
  HostName github.com
  User git
  IdentityFile /home/whoever/.ssh/id_rsa

Then you can add a remote called gh-user1, say, with:

git remote add gh-user1 git@github-as-user1:user1/whatever.git

... and then if you want to push your master branch to the repository user1/whatever on GitHub using the ~/.ssh/id_rsa key, you can just do:

git push gh-user1 master

In order to push as the other user (user2) to the second repository, you need to add a second alias to you ~/.ssh/config file. For example:

Host gh-as-user2
  HostName github.com
  User git
  IdentityFile /home/whoever/.ssh/new/id_rsa

Then to push to that second repository as the different user, you can just do:

git push gh-user2 master