SSH config - same host but different keys and usernames

32

17

I've set up two GitHub accounts, but I can't get ssh keys to work correctly. I've tried various configs.


Host github_username1
    HostName github.com
    IdentityFile ~/.ssh/rsa_1
    User username1
Host github_username2
    HostName github.com
    IdentityFile ~/.ssh/rsa_2
    User username2

git push:

Permission denied (publickey).
fatal: The remote end hung up unexpectedly

Works for username1:

Host github.com
    HostName github.com
    IdentityFile ~/.ssh/rsa_1
    User username1
Host github.com
    HostName github.com
    IdentityFile ~/.ssh/rsa_2
    User username2

git push at username2's repo:

ERROR: Permission to username2/repo.git denied to username1.
fatal: The remote end hung up unexpectedly

I've also tried git push with both IdentityFile and User settings under same Host. The output is the same as with the last config.

I think git automatically searches for Host "github.com" because the remote is such. It is said that Host can be anything you want (https://stackoverflow.com/a/3828682). Is there any way to change what Host from ssh config should specific repo use?

It would be ideal if I could solve this just from ~/.ssh/config.

usr

Posted 2011-12-10T18:59:30.913

Reputation: 535

Answers

46

The OpenSSH client uses only the Host line as the section identifier, and everything else are settings. If you connect to foo@bar.com, SSH will not search for "User foo"; it will only search for "Host bar.com".

In other words: If you have "Host github_username2" in your SSH config, then you must use the same host in your Git remotes – github_username2, not git@github.com.

However, that is not what causes authentication failures, In the case of github.com, the SSH username must be "git". GitHub SSH servers identify users by their SSH key only.


A correct SSH configuration would be:

Host github_username1
    Hostname github.com
    User git
    IdentityFile ~/.ssh/rsa_1
Host github_username2
    Hostname github.com
    User git
    IdentityFile ~/.ssh/rsa_2

Git configuration:

[remote "origin"]
    url = git@github_username1:username2/repo.git

Note: Even though I specified the git username in both places in my example, it only has to be specified once – git@ in Git URL will take priority over User git in SSH config.

user1686

Posted 2011-12-10T18:59:30.913

Reputation: 283 655

2In some cases you might need to add IdentitiesOnly=yes on each host section to make sure ssh will only pick the chosen identity file and don't default / try anything else.. – TCB13 – 2015-12-26T01:19:48.277