Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple SSH keys for different github accounts

Multiple SSH Keys settings for different github account

create different public key

create different ssh key according the article Mac Set-Up Git

$ ssh-keygen -t rsa -C "your_email@youremail.com"

Please refer to github ssh issues for common problems.

for example, 2 keys created at:

~/.ssh/id_rsa_activehacker
~/.ssh/id_rsa_jexchan

then, add these two keys as following

$ ssh-add ~/.ssh/id_rsa_activehacker
$ ssh-add ~/.ssh/id_rsa_jexchan

you can delete all cached keys before

$ ssh-add -D

finally, you can check your saved keys

$ ssh-add -l

Modify the ssh config

$ cd ~/.ssh/
$ touch config
$ subl -a config

Then added

#activehacker account
Host github.com-activehacker
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_activehacker

#jexchan account
Host github.com-jexchan
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_jexchan

Clone you repo and modify your Git config

clone your repo git clone git@github.com:activehacker/gfs.git gfs_jexchan

cd gfs_jexchan and modify git config

$ git config user.name "jexchan"
$ git config user.email "jexchan@gmail.com" 

$ git config user.name "activehacker"
$ git config user.email "jexlab@gmail.com" 

or you can have global git config $ git config --global user.name "jexchan" $ git config --global user.email "jexchan@gmail.com"

then use normal flow to push your code

$ git add .
$ git commit -m "your comments"
$ git push

Another related article in Chinese

  1. http://4simple.github.com/docs/multipleSSHkeys/
@oleweidner

This comment has been minimized.

Copy link

@oleweidner oleweidner commented Sep 3, 2012

I had to change the [remote "origin"] / url field in my local .git/config to use the Host defined in .ssh/config in order for this to work, i.e.,

[remote "origin"]
        url = git@github.com-activehacker:activehacker/gfs.git

Without that modification, git would just try to use my default ssh key.

@sdeverly

This comment has been minimized.

Copy link

@sdeverly sdeverly commented Nov 1, 2012

Had to do the same to get it working.

@elkuku

This comment has been minimized.

Copy link

@elkuku elkuku commented Feb 9, 2013

Me too ๐Ÿ˜‰

@jsh2134

This comment has been minimized.

Copy link

@jsh2134 jsh2134 commented Apr 1, 2013

Me as well.

@straticsryan

This comment has been minimized.

Copy link

@straticsryan straticsryan commented Apr 9, 2013

Instead of having to change the remote origin in the config after cloning, you can just use that custom Host variable on the git clone command instead.

@jmpnot

This comment has been minimized.

Copy link

@jmpnot jmpnot commented May 6, 2013

e.g.

git clone git@github.com-activehacker:activehacker/gfs.git gfs_jexchan
________________________^

as oppose to:

git clone git@github.com:activehacker/gfs.git gfs_jexchan

that's the ticket!

@malleor

This comment has been minimized.

Copy link

@malleor malleor commented Jul 28, 2013

Thanks!

To make it work with Gists, I needed to add another entry in ~/.ssh/config:

Host gist.github.com
  ...
@sgryschuk

This comment has been minimized.

Copy link

@sgryschuk sgryschuk commented Aug 16, 2013

If your ssh keys don't all show up with
ssh-add -l
you have to run
ssh-add ~/.ssh/yourkey.rsa

@mukeshagarwal

This comment has been minimized.

Copy link

@mukeshagarwal mukeshagarwal commented Aug 20, 2013

thanks, worked like a charm

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Aug 28, 2013

but how it can works with "rake deploy" when I deploy my octopress blog? The mapping ssh-key seems no effect....

@nosir

This comment has been minimized.

Copy link

@nosir nosir commented Sep 17, 2013

thanks, would be better if it could be changed as @jmpnot mentioned.

@ptheofan

This comment has been minimized.

Copy link

@ptheofan ptheofan commented Dec 11, 2013

when trying to pull through a php script via exec it would not use the key automatically though it was the correct user configured (my user). Going through the ssh config file just saved the day! :D

@muhammedbasilsk

This comment has been minimized.

Copy link

@muhammedbasilsk muhammedbasilsk commented Jan 16, 2014

ssh config +
updated clone url

Working great... :-) Thanks alot...

@noonat

This comment has been minimized.

Copy link

@noonat noonat commented Jan 28, 2014

I was having an issue with SSH using the wrong key, depending on which order I accessed repositories. Turns out it will try all the keys loaded into ssh-agent in order, and IdentityFile only adds to the end of that list.

You can add IdentitiesOnly yes the SSH config block to force it to only use the IdentityFile you specified.

@avendael

This comment has been minimized.

Copy link

@avendael avendael commented Feb 2, 2014

I was also having issues with SSH using the wrong key even after following the advice of most who have encountered the same issue. In my case, I have a globally enabled ControlMaster in my ssh config. Removing the global ControlMaster config and deleting the github ssh socket (which in my case, is stored in /tmp as ssh_hostname.com_user as specified by my ControlPath config) fixed the issue for me. I can still use ControlMaster in other hosts by adding a ControlMaster auto line in that host's block.

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Feb 16, 2014

@oleweidner: Thank you !

@polykiln

This comment has been minimized.

Copy link

@polykiln polykiln commented Mar 12, 2014

How do you do this with https urls though?

@tejaskanani

This comment has been minimized.

Copy link

@tejaskanani tejaskanani commented Mar 14, 2014

Thanks Jexchan. It helped and working as expected.

@1Rhino

This comment has been minimized.

Copy link

@1Rhino 1Rhino commented Mar 27, 2014

Thank you. It worked fine.

@RBeek

This comment has been minimized.

Copy link

@RBeek RBeek commented May 26, 2014

What exactly is the rule for setting up "Host" in the config file
Is it always github.com-[accountname] or can it be anything, because I set it to the shortname of my repository. Everything works, but it is not quit clear what needs to be set there.

@ignasne

This comment has been minimized.

Copy link

@ignasne ignasne commented May 28, 2014

Tnx it helps a lot!

@ashanbrown

This comment has been minimized.

Copy link

@ashanbrown ashanbrown commented Jun 1, 2014

Thanks for the tips. Might help to add the following to the instructions:

git remote set-url origin git@<host-in-ssh-config>:<username>/<repo>

This is the same as editing your .git/config file.

@greenlaw110

This comment has been minimized.

Copy link

@greenlaw110 greenlaw110 commented Jun 4, 2014

Same question: How do you do this with https urls though?

@gholadr

This comment has been minimized.

Copy link

@gholadr gholadr commented Jun 23, 2014

Thanks for the help!!!

@1ambda

This comment has been minimized.

Copy link

@1ambda 1ambda commented Jun 26, 2014

Awsome!!!!!!!!

@wmyers

This comment has been minimized.

Copy link

@wmyers wmyers commented Jul 2, 2014

Thanks worked a treat. The following worked for me:
git clone git@github.com-sshID:myGitHubAccount/myRepo.git

@robbyronk

This comment has been minimized.

Copy link

@robbyronk robbyronk commented Aug 1, 2014

๐Ÿ‘

@nikolasc

This comment has been minimized.

Copy link

@nikolasc nikolasc commented Aug 4, 2014

I forked @RichardBronosky (by mistake :) ) and changed the Host and User settings in ~/.ssh/config (User ) which enables one to actually use multiple accounts, on the local machine, with SSH access.

I borrowed one of my friend's laptops, and created a github account. It took a while to figure out why I kept getting kicked off github 'as user <friend's username>' - he hadn't created a new user for me on the laptop, so I was accessing with his username set in ~/.gitconfig and used with SSH. So the above, along with my ssh config changes, was the best way to get around the issue without wrecking his setup.

@zhangcheng

This comment has been minimized.

Copy link

@zhangcheng zhangcheng commented Aug 16, 2014

I just found out another way no need to deal with multiple SSH keys: use gitcredentials's useHttpPath option

[credential]
    helper = osxkeychain
    useHttpPath = true

English see http://www.davidhayden.org/blog/multiple-github-accounts-git-credential-osxkeychain
Chinese see http://jianshu.io/p/ef394ef6df95

@plato-cambrian

This comment has been minimized.

Copy link

@plato-cambrian plato-cambrian commented Sep 18, 2014

On Windows 7, I want to manage multiple github users with passphrase-protected ssh keys.

I sorted my ~.ssh/config file to use different keys for different repo domains as described above (I previously documented the steps on mint/ubuntu.)

However, I don't want to type my passphrase every time, and I don't want to use ssh-agent.

Here's how I set up Pageant to ask for and remember my passphrase on Windows login:

  • Download the Putty Tools package
  • Win+R to open run dialog
  • shell:startup to open the auto start folder in windows explorer
  • Navigate to your Pageant folder in a separate Explorer window
  • Right click and drag PAGEANT.EXE to the Startup folder. Choose Create Shortcut
  • Right click the shortcut, properties, Shortcut tab
  • Find the path to your .ppk encoded keypair
    • generate one with PUTTYGEN.EXE if you need a new one
    • convert one with PUTTYGEN.EXE if you have a linux id_rsa file but no .ppk
    • win7+ : shift right click your key in Explorer, Copy as path
  • Append the key path to the C:\whatever\PAGEANT.EXE line
    • e.g: "Target: C:\putty\PAGEANT.EXE plato_cambrian.ppk plato.ppk"
    • If your keys aren't adjacent to PAGEANT you can use absolute paths or change "Start in:" which is Pageant's CWD
  • Open the shortcut or reboot, and type your passphrases
@frostwire

This comment has been minimized.

Copy link

@frostwire frostwire commented Oct 22, 2014

Let's say alice is a github.com user, with 2 or more private repositories repoN.
For this example we'll work with just two repositories named repo1 and repo2

https://github.com/alice/repo1

https://github.com/alice/repo2

You need to be to pull from these repositories without entering a passwords probably on a server, or on multiple servers.
You want to perform git pull origin master for example, and you want this to happen without asking for a password.

You don't like dealing with ssh-agent, you have discovered (or you're discovering now) about ~/.ssh/config a file that let's your ssh client know what private key to use depending on Hostname and username, with a simple configuration entry that looks like this:

Host github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/alice_github.id_rsa
  IdentitiesOnly yes

So you went ahead and created your (alice_github.id_rsa, alice_github.id_rsa.pub) keypair, you then also went to your repository's .git/config file and you modified the url of your remote origin to be something like this:

[remote "origin"]
        url = "ssh://git@github.com/alice/repo1.git"

And finally you went to the repository Settings > Deploy keys section and added the contents of alice_github.id_rsa.pub

At this point you could do your git pull origin master without entering a password without issue.

but what about the second repository?

So your instinct will be to grab that key and add it to repo2's Deploy keys, but github.com will error out and tell you that the key is already being used.

Now you go and generate another key (using ssh-keygen -t rsa -C "alice@alice.com" without passwords of course), and so that this doesn't become a mess, you will now name your keys like this:

  • repo1 keypair: (repo1.alice_github.id_rsa, repo1.alice_github.id_rsa.pub)
  • repo2 keypair: (repo2.alice_github.id_rsa, repo2.alice_github.id_rsa.pub)

You will now put the new public key on repo2's Deploy keys configuration at github.com, but now you have an ssh problem to deal with.

How can ssh tell which key to use if the repositories are hosted on the same github.com domain?

Your .ssh/config file points to github.com and it doesn't know which key to use when it's time to do the pull.

So I found a trick with github.com. You can tell your ssh client that each repository lives in a different github.com subdomain, in these cases, they will be repo1.github.com and repo2.github.com

So first thing is editing the .git/config files on your repo clones, so they look like this instead:

For repo1

[remote "origin"]
        url = "ssh://git@repo1.github.com/alice/repo1.git"

For repo2

[remote "origin"]
        url = "ssh://git@repo2.github.com/alice/repo2.git"

And then, on your .ssh/config file, now you will be able to enter a configuration for each subdomain :)

Host repo1.github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/repo1.alice_github.id_rsa
  IdentitiesOnly yes

Host repo2.github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/repo2.alice_github.id_rsa
  IdentitiesOnly yes

Now you are able to git pull origin master without entering any passwords from both repositories.

If you have multiple machines, you could copy the keys to each of the machines and reuse them, but I'd advise doing the leg work to generate 1 key per machine and repo. You will have a lot more keys to handle, but you will be less vulnerable if one gets compromised.

@burningTyger

This comment has been minimized.

Copy link

@burningTyger burningTyger commented Nov 6, 2014

Let me add that it is not enough to have

Host repo1.github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/repo1.alice_github.id_rsa
  IdentitiesOnly yes

 Host github.com
   HostName github.com
   User git
   IdentityFile /home/alice/.ssh/repo2.alice_github.id_rsa
   IdentitiesOnly yes

In this case the repo1 block will point to the second github.com block because the repo1 block says HostName github.com which will redirect from first to second block.

Took me a while to figure out just how smart ssh is ๐Ÿ˜„

@brentsony

This comment has been minimized.

Copy link

@brentsony brentsony commented Nov 25, 2014

@burningTyger The HostNames can be identical - it is the 'Host' that must differ. What may work best is to use "repo2.github.com", instead of that second "github.com". Then clone with git clone git@repo2.github.com:GitHubUserName/RepoName.git

@elpd

This comment has been minimized.

Copy link

@elpd elpd commented Dec 24, 2014

Thank you. Worked as expected.

@pajtai

This comment has been minimized.

Copy link

@pajtai pajtai commented Jan 28, 2015

thank you @oleweidner for the tip on changing the git config!

@dbolser

This comment has been minimized.

Copy link

@dbolser dbolser commented Feb 19, 2015

Thanks dudels.

@apiraino

This comment has been minimized.

Copy link

@apiraino apiraino commented Mar 6, 2015

Thanks for the guide, helped me solve this very issue. I need a public keys for each of my GitHub repos.

go figure....

@lazurey

This comment has been minimized.

Copy link

@lazurey lazurey commented Jul 7, 2015

Thank you Xianjun!!!
Your answer is the first one when I searched this problem on google. ๐Ÿ˜„

@micheleva

This comment has been minimized.

Copy link

@micheleva micheleva commented Aug 22, 2015

Thank you very much for the instructions @jexchan ! Doing as @jmpnot wrote fixed all the problems !

@AkhterAli

This comment has been minimized.

Copy link

@AkhterAli AkhterAli commented Aug 28, 2015

Thank you so much for this guide, this worked wonders with my sublime text git plugin!

@ttiu

This comment has been minimized.

Copy link

@ttiu ttiu commented Nov 5, 2015

Works great. Thank you!

@rplaurindo

This comment has been minimized.

Copy link

@rplaurindo rplaurindo commented Nov 6, 2015

$ git config --local remote.origin.url git@[repository]-[public_ssh_key_file_name]:[repository_user]/[project].git
$ git config --local user.email [user_email]

Works!!! ^^

The .git file looks like this

[remote "origin"]
  url = git@[repository]-[public_ssh_key_file_name]:[repository_user]/[project].git
@StylusEater

This comment has been minimized.

Copy link

@StylusEater StylusEater commented Nov 17, 2015

I think others have mentioned this but I couldn't find it when I searched the page.

I was getting the following error on bitbucket:

$ git push -u origin master
conq: repository access denied.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.`

adding this to the ~/.ssh/config file entries after specifying IdentityFile fixed it ...

IdentitiesOnly yes

Contents of ~/.ssh/config:

Host bitbucket.org-foo
HostName bitbucket.org
User git
IdentityFile ~/.ssh/my_rsa_private_key
IdentitiesOnly yes

Contents of .git/config:

[remote "origin"]
>url = git@bitbucket.org-foo:repo/repo.git
>fetch = +refs/heads/:refs/remotes/origin/

Notice how bitbucket.org-foo matches in each.

@bigomega

This comment has been minimized.

Copy link

@bigomega bigomega commented Nov 30, 2015

AT LAST, I've seen someone else use subl command. I'm not alone ๐Ÿ˜„

@wching

This comment has been minimized.

Copy link

@wching wching commented Jan 19, 2016

@ashanbrown thanks for your line, saved me ๐Ÿ‘ ๐Ÿš€

@blog-han-chen

This comment has been minimized.

Copy link

@blog-han-chen blog-han-chen commented Jan 31, 2016

[remote "origin"]
url = git@github.com-activehacker:activehacker/gfs.git

Golden line, solved the problem.

@vidinev

This comment has been minimized.

Copy link

@vidinev vidinev commented Feb 16, 2016

On Ubuntu 15.10 I faced with โ€œBad owner or permissions on ~/.ssh/configโ€ error.
This article helped me http://serverfault.com/questions/253313/ssh-hostname-returns-bad-owner-or-permissions-on-ssh-config

Just need:
chmod 600 ~/.ssh/config

@raduvargabuddyguard

This comment has been minimized.

Copy link

@raduvargabuddyguard raduvargabuddyguard commented Feb 17, 2016

What worked for me is to use "github-activehacker" instead of "github.com-activehacker".

@Khande

This comment has been minimized.

Copy link

@Khande Khande commented Aug 25, 2016

learned a lot, thx!

@cdarne-darwineco

This comment has been minimized.

Copy link

@cdarne-darwineco cdarne-darwineco commented Sep 7, 2016

Worked pretty good, thanks!

@adeyahya

This comment has been minimized.

Copy link

@adeyahya adeyahya commented Sep 22, 2016

Thanks, it worked pretty awesome!

@eness

This comment has been minimized.

Copy link

@eness eness commented Jan 14, 2017

Worked fine for me!

@knatch

This comment has been minimized.

Copy link

@knatch knatch commented Jan 19, 2017

Thanks @oleweidner !!

@spasarok

This comment has been minimized.

Copy link

@spasarok spasarok commented Jan 30, 2017

If you have to change your local .git/config for this to work, how are you supposed to make the first clone?

EDIT: I figured it out. Instead of changing the remote url in .git/config, you can clone by replacing github.com with the host like so: git clone git@github.com-activehacker:activehacker/gfs.git gfs_jexchan. This will automatically set the remote url in .git/config to use the ssh host, so no need to manually edit after cloning.

@ORESoftware

This comment has been minimized.

Copy link

@ORESoftware ORESoftware commented Feb 3, 2017

this is going to save my life!

@irajhedayati

This comment has been minimized.

Copy link

@irajhedayati irajhedayati commented Feb 7, 2017

Thank you for the documentation. It helped me. Could you please apply @oleweidner changes as well. It seems it is mandatory.

@JREAM

This comment has been minimized.

Copy link

@JREAM JREAM commented Feb 23, 2017

I find this really easy

Example

git clone gh:jream/config-ubuntu.git

~/.gitconfig

[url "git@github.com:"]
     insteadOf = "gh:"
     pushInsteadOf = "github:"
     pushInsteadOf = "git://github.com/"

[url "git://github.com/"]
     insteadOf = "github:"

~/.ssh/config

Host github.com                                                             
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_rsa
@v2b1n

This comment has been minimized.

Copy link

@v2b1n v2b1n commented Feb 23, 2017

+1

@lepetitchevalblanc

This comment has been minimized.

Copy link

@lepetitchevalblanc lepetitchevalblanc commented Jun 8, 2017

With a git push, if underlying ssh returns an error as "nodename or servname" unknown replace the ":" by a / in the origin url, like
(git config --get remote.origin.url) ssh://git@github.com-[reponame]/[username]/[reponame].git (at least with git 2.11.0)

@inakiabt

This comment has been minimized.

Copy link

@inakiabt inakiabt commented Jul 14, 2017

I finally made it work! ๐ŸŽ‰
The issue in my case (I think it's related to https://gist.github.com/jexchan/2351996#gistcomment-998128) was that I had this in my ~/.ssh/config (it's to make ssh connections persistent):

Host * !localhost
  ControlPath ~/tmp/ssh_mux_%h_%p_%r
  ControlMaster auto
  ControlPersist 2h

Whenever I connect to a server via SSH, that configuration checks if the files exists in ~/tmp if not, it creates a new one. But if it exists, it reuses the latest connection that created that file (I'm not pretty sure how exactly works, but it's something like that). With that ControlPath configuration, it creates files like: ~/tmp/ssh_mux_github.com-22-git because %h is for "remote host", %p is for "port" and %r is for "ssh user". So, no matter which repository hostname I used, the "remote host" was always github.com (because of the HostName github.com configuration this gist suggest) and the connection was reused every time.

The trick was change my ~/.ssh/config from ControlPath ~/tmp/ssh_mux_%h_%p_%r to ControlPath ~/tmp/ssh_mux-%n-%p-%r.
%n is for "local hostname" (the Host config), so now this control path file is created like ~/tmp/ssh_mux_github.com-activehacker-22-git.

@DawnImpulse

This comment has been minimized.

Copy link

@DawnImpulse DawnImpulse commented Aug 20, 2017

I was using the user as my github username rather than git . Hence having problems with connection . Now everything working perfectly . Thanks a lot .

@GraniteConsultingReviews

This comment has been minimized.

Copy link

@GraniteConsultingReviews GraniteConsultingReviews commented Aug 28, 2017

I was facing problems but thank god this works properly. Thanks for sharing

@vbauerster

This comment has been minimized.

@cwangmove

This comment has been minimized.

Copy link

@cwangmove cwangmove commented Sep 15, 2017

Thank you, JexChan! This post is really helpful.

According to my experiment, git config user.name "myusername" and git config user.email "my@email.com" does NOT matter at all. What really matters is what oleweidner mentioned in the first comment of this post as following:

`I had to change the [remote "origin"] / url field in my local .git/config to use the Host defined in .ssh/config in order for this to work, i.e.,

[remote "origin"]
url = git@github.com-activehacker:activehacker/gfs.git
Without that modification, git would just try to use my default ssh key.`

In addition, if your url from git hub is git@github.com:activehacker/gfs.git, when doing git clone, you need to do
$ git clone git@github.com-activehacker:activehacker/gfs.git

@navyad

This comment has been minimized.

Copy link

@navyad navyad commented Sep 25, 2017

following worked for me:

  • update url for origin in .git/config as given for HOST in /.ssh/config
  • git config user.email
  • git config user.name
@jagroop

This comment has been minimized.

Copy link

@jagroop jagroop commented Nov 29, 2017

thanks mate ๐Ÿ‘ ๐Ÿ’ฏ

@gaborod16

This comment has been minimized.

Copy link

@gaborod16 gaborod16 commented Jan 8, 2018

Guys, hope you won't lose as much time as I did to realize that I just had to reopen the console.
If you have all set up correctly and all of the sudden it stops working, just close and open your console and try again.

So sad...

@ranjitis

This comment has been minimized.

Copy link

@ranjitis ranjitis commented Jan 15, 2018

Another solution is to only have one active ssh key in the ssh-agent.

Example ssh config-file:
Host www.github.com
โ€‚ โ€‚ ForwardAgent yes
โ€‚ โ€‚ User jexchan

Only use one key in the ssh-agent at any time:
$ ssh-add -D
$ ssh-add ~/.ssh/id_rsa_jexchan

Change user:
$ ssh-add -D
$ ssh-add ~/.ssh/id_rsa_activehacker

@L4grange

This comment has been minimized.

Copy link

@L4grange L4grange commented Jan 31, 2018

Thank you so much, I finally set up both of my keys, ssh config and remote URLs correctly, I've been struggling for months when pushing projects to different accounts and finally everything is working!

@tannhaeuser

This comment has been minimized.

Copy link

@tannhaeuser tannhaeuser commented Feb 12, 2018

...just removed my stupid comment here as I learned something the hard way...

Usually a Host-section could contain more than one IdentityFile entry - and a plain SSH connection will usually probe all keys in the given order until it finds one that can be used.

The same is true for cloning public repositories from github. It will ignore unknown keys in the config (not known to github at all) and accepts the first known key in the chain.

But if you try to push to a repository github bails out on the first unknown key or a key that is not associated with the targeted repo.

@TiE23

This comment has been minimized.

Copy link

@TiE23 TiE23 commented Feb 16, 2018

Keychain cannot remember your passwords in MacOS when using this trick?

I ran into this issue as a MacOS user. I use ssh-add -K to have MacOS's KeyChain remember my passwords to my two SSH keys. Yet I would still be asked for a password when pushing my change in my second account or other some such issue.

See. I traced it back... If you add the identity like so:

cd ~/.ssh;
ssh-add -K private.rsa;

And then in your .ssh/config file define your IdentityFile's absolute path (like I did):

  IdentityFile /Users/jdoe/.ssh/private.rsa
  IdentitiesOnly yes

It won't work. In the mind of the ssh agent and KeyChain private.rsa and /Users/jdoe/.ssh/private.rsa are different and will ask you for the password when trying to pull/push.

No, you need to be consistent with how you add the password to the keychain. Add your Identity with ssh-add -K /Users/jdoe/.ssh/private.rsa

(I use absolute path /Users/jdoe/ instead of ~/ just because I felt like it. I believe ~/ should work just fine.)

To fix this open up KeyChain Access in MacOS, search your keychain for your SSH keys and after reminding yourself of the passwords (you can look at them in KeyChain Access) delete them. Then re-add the Identities using ssh-add -K /Users/jdoe/.ssh/private.rsa. That should fix things up.

@ann07cor

This comment has been minimized.

Copy link

@ann07cor ann07cor commented Feb 19, 2018

Had to do the same to get it working. My friend, web developer from web development company helped me to solve it. He's a former programmer, has a huge experience in creating and optimizing more than 2,000 websites for small to mid-sized companies throughout the United States, so he usually gives me pieces of advice, cause I'm just the beginner..

@anhducbkhn

This comment has been minimized.

Copy link

@anhducbkhn anhducbkhn commented Mar 8, 2018

Work well. (Y)

@arsmuun

This comment has been minimized.

Copy link

@arsmuun arsmuun commented Mar 23, 2018

Worked good for me, thanks. Also had to match the origin url to the host url in config.

@brlafreniere

This comment has been minimized.

Copy link

@brlafreniere brlafreniere commented Apr 28, 2018

What is the subl command? It doesn't exist on my machine.

@DevinFrenze

This comment has been minimized.

Copy link

@DevinFrenze DevinFrenze commented May 2, 2018

@brlafreniere it's the command for opening sublime

@ronapelbaum

This comment has been minimized.

Copy link

@ronapelbaum ronapelbaum commented May 10, 2018

๐Ÿ‘

@Lathanao

This comment has been minimized.

Copy link

@Lathanao Lathanao commented Jun 8, 2018

Thanks!

@antonlpr

This comment has been minimized.

Copy link

@antonlpr antonlpr commented Jun 15, 2018

DANKE!1

@ctessmer

This comment has been minimized.

Copy link

@ctessmer ctessmer commented Aug 9, 2018

@ashanbrown: Your syntax was way cleaner than OPs. Totally helped my brain figure it out. Thank you!! ๐Ÿฅ‡

@valerihristovsolarwinds

This comment has been minimized.

Copy link

@valerihristovsolarwinds valerihristovsolarwinds commented Aug 27, 2018

Thanks man! I had to create a new SSH key for a project and the git clone did not work. After I "ssh-add" the private key, git clone worked as the key was registered. :)

@tkshnwesper

This comment has been minimized.

Copy link

@tkshnwesper tkshnwesper commented Sep 19, 2018

Thanks for the tips. Might help to add the following to the instructions:

git remote set-url origin git@<host-in-ssh-config>:<username>/<repo>

This is the same as editing your .git/config file.

Thank you @ashanbrown! That solved my problem

@cryptCEE

This comment has been minimized.

Copy link

@cryptCEE cryptCEE commented Oct 8, 2018

What is the subl command? It doesn't exist on my machine.

it opens up the sublime text editor :-)

@ratiotile

This comment has been minimized.

Copy link

@ratiotile ratiotile commented Nov 15, 2018

me: how is appending -my_username to the github url supposed to work?
oh wait, it doesn't:
ssh: Could not resolve hostname github.com-username: nodename nor servname provided or not known

@bitspittle

This comment has been minimized.

Copy link

@bitspittle bitspittle commented Nov 24, 2018

How is everyone getting this to work?

Anytime I try to clone, push, pull etc. from "git@github.com-username", I get an error message: nodename nor servname provided, or not known

Edit: Got this to work. If you're seeing this error message, it probably means you forgot to include the HostName github.com line in your ~/.ssh/config

@roes-mekari

This comment has been minimized.

Copy link

@roes-mekari roes-mekari commented Nov 27, 2018

Command "ssh-add -D" saved me from wrong git account because ssh multiplex connection. Thanks!

@alxpck

This comment has been minimized.

Copy link

@alxpck alxpck commented Jan 23, 2019

So helpful, thank you! Like many other people above, I also needed to add IdentitiesOnly yes to the global config file for this to work. Full working example from @RichardBronsky

@ernestkamara

This comment has been minimized.

Copy link

@ernestkamara ernestkamara commented Feb 4, 2019

Thanks. ๐Ÿ‘

@anToha

This comment has been minimized.

Copy link

@anToha anToha commented Feb 17, 2019

I've got a problem that when you have an entry

Host *
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/id_rsa

Then it will override your custom identities even if you were using IdentitiesOnly yes. Commenting out this part of config made everything work again. I wonder if I've broke something with it though. We'll see :)

@zhao-ji

This comment has been minimized.

Copy link

@zhao-ji zhao-ji commented Feb 27, 2019

Yeah, ssh-config host must match the host name in .git/config.
Thanks a lot!

@yinzara

This comment has been minimized.

Copy link

@yinzara yinzara commented Apr 4, 2019

I've rewritten this guide to include changes from Git 2.13 that allow this to be managed in a much easier fashion.
See https://gist.github.com/yinzara/bbedc35798df0495a4fdd27857bca2c1

@TuanLuu54

This comment has been minimized.

Copy link

@TuanLuu54 TuanLuu54 commented Apr 22, 2019

Thanks! :bow

@freemh

This comment has been minimized.

Copy link

@freemh freemh commented Jun 21, 2019

You can add ssh -vT git@github.com as the final step to check if you can connect

@linjiejunChina

This comment has been minimized.

Copy link

@linjiejunChina linjiejunChina commented Aug 9, 2019

I had to change the [remote "origin"] / url field in my local .git/config to use the Host defined in .ssh/config in order for this to work, i.e.,

[remote "origin"]
        url = git@github.com-activehacker:activehacker/gfs.git

Without that modification, git would just try to use my default ssh key.

Me too

@mfaizan1

This comment has been minimized.

Copy link

@mfaizan1 mfaizan1 commented Aug 20, 2019

I followed this

generated and added the ssh for user1
generated and added the ssh for user2
now all git actions are being performed by user2
like if i have a project that is related to user1 , when i try to push code it gives error permission denied for user: user2

how can i switch users ?

@WhoJave

This comment has been minimized.

Copy link

@WhoJave WhoJave commented Aug 23, 2019

Nice It works for me.

@bibel24

This comment has been minimized.

Copy link

@bibel24 bibel24 commented Oct 6, 2019

+1

@bradydowling

This comment has been minimized.

Copy link

@bradydowling bradydowling commented Nov 15, 2019

Here's another guide that might be helpful for others (uses ssh-add).

@rahulverma283

This comment has been minimized.

Copy link

@rahulverma283 rahulverma283 commented Apr 20, 2020

We need to add the newly created ssh keys, to our GitHub accounts as well, hence the auth will fail.
This blog works flawlessly - https://code.tutsplus.com/tutorials/quick-tip-how-to-work-with-github-and-multiple-accounts--net-22574

@raffienficiaud

This comment has been minimized.

Copy link

@raffienficiaud raffienficiaud commented May 2, 2020

Here is an extensive review on various methods for configuring SSH: https://yayimorphology.org/ssh-identities-made-easy.html

@emaysyuk

This comment has been minimized.

Copy link

@emaysyuk emaysyuk commented Jun 20, 2020

me: how is appending -my_username to the github url supposed to work?
oh wait, it doesn't:
ssh: Could not resolve hostname github.com-username: nodename nor servname provided or not known

Make sure you specified URL to your remote in SSH format:
git@github.com-username:username/repo.git (correct)
https://github.com-username/username/repo.git (wrong)

Adjust your remote if needed:
git remote remove origin
git remote add origin git@github.com-username:username/repo.git

@moshe-quantz

This comment has been minimized.

Copy link

@moshe-quantz moshe-quantz commented Jul 15, 2020

DO THAT Host github.com:activehacker INSTEAD Host github.com-activehacker
(replace - with :)

Complete example

#activehacker account
Host github.com:activehacker
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_activehacker

#jexchan account
Host github.com:jexchan
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_jexchan
@curbengh

This comment has been minimized.

Copy link

@curbengh curbengh commented Jul 25, 2020

https://gist.github.com/jexchan/2351996#gistcomment-2353604
In the mind of the ssh agent and KeyChain private.rsa and /Users/jdoe/.ssh/private.rsa are different and will ask you for the password when trying to pull/push.
(I use absolute path /Users/jdoe/ instead of ~/ just because I felt like it. I believe ~/ should work just fine.)

ssh agent also treats /home/user and ~/ as different. If ~/ is used in the ssh config, then ssh-add ~/.ssh/id_rsa_user should be used.

@arc113

This comment has been minimized.

Copy link

@arc113 arc113 commented Jul 28, 2020

thanks, worked like a charm

didn't work for me. The problem I'm facing is that I need to add all other keys to the agent manually using eval ssh-agent and then ssh-add /key/ .

@Drjacky

This comment has been minimized.

Copy link

@Drjacky Drjacky commented Aug 7, 2020

e.g.

git clone git@github.com-activehacker:activehacker/gfs.git gfs_jexchan
________________________^

as oppose to:

git clone git@github.com:activehacker/gfs.git gfs_jexchan

that's the ticket!

@jmpnot Do you know another way without changing ssh address? I want to use the same as the one I copy from repo clone section. provided by Github.

@leddzip

This comment has been minimized.

Copy link

@leddzip leddzip commented Aug 12, 2020

@Drjacky you might need to configure your ~/.gitconfig file. My setup for identity A and identity B is the following:

for ~/.gitconfig

[includeIf "gitdir:~/Dev/Perso/"]
        path = ~/Dev/Perso/.gitconfig-personal
[includeIf "gitdir:~/Dev/Public/"]
        path = ~/Dev/Public/.gitconfig-public

for ~/Dev/Perso/.gitconfig-personal:

[user]
	name = A
	email = A@gmail.com
[core]
	sshCommand = ssh -i ~/.ssh/id_rsa_A -F /dev/null

and for ~/Dev/Public/.gitconfig-public:

[user]
	name = B
	email = B@gmail.com
[core]
	sshCommand = ssh -i ~/.ssh/id_rsa_B -F /dev/null

that way, each time you work in your identity A subdirectory, you'll have the identity A (name and mail) as well as the related ssh key. And in your identity B subdirectory, well, you'll be B by name, mail and ssh key...

you don't need to mess up the repo url to match some config from your ssh profile.

Note that those come from git 2.10 (2016) for sshCommand and git 2.14 (2017) for includeIf so it was not available at the time this gist and most of the answer were posted.

@digglife

This comment has been minimized.

Copy link

@digglife digglife commented Aug 14, 2020

I had to change the [remote "origin"] / url field in my local .git/config to use the Host defined in .ssh/config in order for this to work, i.e.,

[remote "origin"]
        url = git@github.com-activehacker:activehacker/gfs.git

Without that modification, git would just try to use my default ssh key.

Indeed. Thank you!

@Drjacky

This comment has been minimized.

Copy link

@Drjacky Drjacky commented Aug 15, 2020

@Drjacky you might need to configure your ~/.gitconfig file. My setup for identity A and identity B is the following:

for ~/.gitconfig

[includeIf "gitdir:~/Dev/Perso/"]
        path = ~/Dev/Perso/.gitconfig-personal
[includeIf "gitdir:~/Dev/Public/"]
        path = ~/Dev/Public/.gitconfig-public

for ~/Dev/Perso/.gitconfig-personal:

[user]
	name = A
	email = A@gmail.com
[core]
	sshCommand = ssh -i ~/.ssh/id_rsa_A -F /dev/null

and for ~/Dev/Public/.gitconfig-public:

[user]
	name = B
	email = B@gmail.com
[core]
	sshCommand = ssh -i ~/.ssh/id_rsa_B -F /dev/null

that way, each time you work in your identity A subdirectory, you'll have the identity A (name and mail) as well as the related ssh key. And in your identity B subdirectory, well, you'll be B by name, mail and ssh key...

you don't need to mess up the repo url to match some config from your ssh profile.

Note that those come from git 2.10 (2016) for sshCommand and git 2.14 (2017) for includeIf so it was not available at the time this gist and most of the answer were posted.

I already do that but, it doesn't take SSH keys related to each folder/project.
https://stackoverflow.com/questions/63307136/git-includeif-not-working-with-git-clone/63308511

@leddzip

This comment has been minimized.

Copy link

@leddzip leddzip commented Aug 15, 2020

@Drjacky If I read carefully the stackoverflow post, it seems you are missing the core.sshCommand. You do change the user name and mail for your company related folder, but you have to include the sshCommand to tell git which ssh key you want to use. Note that this solution doesn't require to alter your .ssh/config file.

@Drjacky

This comment has been minimized.

Copy link

@Drjacky Drjacky commented Aug 15, 2020

@Drjacky If I read carefully the stackoverflow post, it seems you are missing the core.sshCommand. You do change the user name and mail for your company related folder, but you have to include the sshCommand to tell git which ssh key you want to use. Note that this solution doesn't require to alter your .ssh/config file.

You were right! Thanks! It works: https://stackoverflow.com/a/63308511/421467

@blaxpy

This comment has been minimized.

Copy link

@blaxpy blaxpy commented Aug 31, 2020

Solution for multiple SSH keys without changing a git repository url when cloning it.
Full answer https://stackoverflow.com/a/63676323/8721990.

~/.gitconfig or ~/.config/git/config:

[url "git@github-user1:user1"]
    insteadOf = git@github.com:user1

~/.ssh/config:

AddKeysToAgent  yes
IdentitiesOnly yes

Host github-user1
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_user1
@bradydowling

This comment has been minimized.

Copy link

@bradydowling bradydowling commented Aug 31, 2020

Looks like there a several gotchas and @jexchan isn't maintaining this gist anymore. Anyone know of a good fork that is kept up to date with relevant instructions, info, and FAQs? Something so people don't have to read through every comment in this thread :)

@rkochar

This comment has been minimized.

Copy link

@rkochar rkochar commented Oct 4, 2020

idk if anybody has posted this here. It has two much simpler solutions.

@peretzagency

This comment has been minimized.

Copy link

@peretzagency peretzagency commented Oct 12, 2020

Thank you for the great material. It was very useful for me as a specialist of https://peretz.agency/

@k-o-d-r

This comment has been minimized.

Copy link

@k-o-d-r k-o-d-r commented Oct 19, 2020

surprisingly nobody said (or probably I just missed the thing?) that since your config looks smth like

Host bruh
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_whatever

instead of doing this
git clone git@github.com:pepe/area45docs.git

you can just go
git clone bruh:pepe/area45docs.git

you don't need git@github.com, as both user 'git' and host name 'github.com' are already describing your 'bruh' host, so whenever you use 'bruh' as host, user and host name are automatically retrieved from the config

@rkochar

This comment has been minimized.

Copy link

@rkochar rkochar commented Oct 20, 2020

That would mean changing the .git/config file every time right? Much much simpler to assign keys by directory so that any project cloned to the directory will by default use a particular ssh key.

@SuwakoMmh

This comment has been minimized.

Copy link

@SuwakoMmh SuwakoMmh commented Oct 30, 2020

I figured that one might want git to try to connect using a list of private keys and use the one that just works, so I made a tutorial
https://gist.github.com/SuwakoMmh/0b53f081d17c51189900f809e25dcc62
Hope that helps some of you !

@medmin

This comment has been minimized.

Copy link

@medmin medmin commented Oct 31, 2020

If your ssh keys don't all show up with
ssh-add -l
you have to run
ssh-add ~/.ssh/yourkey.rsa

7 years later, your reply is still saving lives. My Salute๏ผ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You canโ€™t perform that action at this time.