I have 2 GitHub account and I can't use the same public key for both accounts. I have already generated 2 ssh key
C:\Users\{User_Name}\.ssh\id_rsa
C:\Users\{User_Name}\.ssh\id_rsa_another
My question is, how I can use multiple ssh keys for Windows? On Linux, I just have to add by using ssh-add
command, but on Windows, this command does not exist.
What have I done to make the other ssh key work, I have to change the id_rsa
to id_rsa_temp
and id_rsa_another
to id_rsa
. I know this is stupid.
CodePudding user response:
First, ssh-add exists on Windows, as part of Git For Windows:
C:\Users\vonc>where ssh-add
C:\Program Files\Git\usr\bin\ssh-add.exe
It is needed for caching the passphrase protecting a private key (which is not always needed, since you can create a private key without passphrase)
Using different account, as commented, uses a %USERPROFILE%.ssh\config file, with in it:
Host gh1
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa
Host gh2
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa_another
You can test them with:
ssh -Tv gh1
ssh -Tv gh2
You should see a different "Welcome" message per key.
And the URL to use for cloning your repo would be:
gh1:user1/repo1
gh2:user2/repo2
If, and only if, your private ssh keys are encrypted (protected by a passphrase), then you need a .bashrc to start the SSH agent, and register your keys in it, effectively caching said keys.
See "Auto-launching ssh-agent on Git for Windows"
You can run
ssh-agent
automatically when you open bash or Git shell.
Copy the following lines and paste them into your~/.bashrc
(%USERPROFILE%/.bashrc
) file in Git shell:
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
ssh-add ~/.ssh/id_rsa_another
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
ssh-add ~/.ssh/id_rsa_another
fi
unset env
You will have to enter the passphrase on the first start, then no more: said passphrase will be cached by the agent.
CodePudding user response:
Finally, I found the solution
I have to use Git Bash because I can't use a regular Windows terminal when running this command
$ eval $(ssh-agent -s)
And then I can add the SSH key by running this command
$ ssh-add C:/Users/{User_Name}/.ssh/id_rsa_another
We must use the forward-slash for the path