SSH config - same host but different keys and usernames
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.
The OpenSSH client uses only the Host
line as the section identifier, and everything else are settings. If you connect to [email protected]
, 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 [email protected]
.
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
Alternative Git configuration:
[remote "origin"]
url = [email protected]:username2/repo.git
[url "git@github_username1:"]
insteadOf = [email protected]:
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.