How can I access one Git repo from two machines?

2020-08-01 01:36发布

问题:

I have a repo for work, normally accessed from my work machine. On that machine, I have created an SSH key-pair using ssh-keygen in Git Bash. The key-pair on both machines is id_rsa and id_rsa.pub.

If I log in as my work user, and try to add my home key to the work user account, I get told somebody else has already registered that key. If I generate a second home key, i.e. id_rsa2 and id_rsa.pub2, I get an authentication failure.

From this, I surmise that Git, by default, only looks for and uses the original id_rsa.pub file when authenticating with the repo host, which incidentally, is BitBucket. I'm guessing I somehow have to tell Git which key to use for which repo, or something, but right now I am lost and asking how to do this.

回答1:

You can use multiple private ssh keys using a ~/.ssh/config file.

Host fromhome
  HostName yourServer
  User git
  IdentityFile "~/.ssh/id_rsa2"

Host fromwork
  HostName yourServer 
  User git
  IdentityFile "~/.ssh/id_rsa"

That file can reference both private keys and let you use 2 different ssh urls.

From Home:

cd /path/to/local/repo
git remote set-url origin fromhome:<user>/yourrepo

From work:

cd /path/to/local/repo
git remote set-url origin fromwork:<user>/yourrepo

That being said, from home or work, you only need one set of public/private key, so you don't need the config file.
If you regenerate a private id_rsa private key at home, you will be able to register its new public key on BitBucket side.
At home, the .ssh/config is only useful if you had already a private/public ssh key used for something else.

Rahul Gupta asks:

Why can't I just copy the .ssh directory to the second machine and use the same?

This is considered as bad practice: a private key is supposed to remain... private, as in "not copied around".
Plus you can easily revoke a private key (by removing its authorized key from the .authorized_keys ssh server). If the private key was used on many machines, you would revoke access for way more than you intended by removing one public key on the server side.



标签: git ssh