在GitHub/Bitbucket上使用多个账户/身份进行推送

6
我在 Github/Bitbucket 上拥有多个账户,并为每个账户设置了唯一的私钥和公钥。当我需要向这些不同账户创建的代码库推送代码时,我几乎肯定会遇到访问被拒绝的问题,除非我将代码推送到默认账户(即我最初创建的那个账户)。
有没有办法在推送之前切换到不同的凭证?我正在 Macintosh 机器上使用 Source Tree。我不想每次推送时手动重命名 `~/.ssh/id_rsa`。
非常感谢您的帮助!

现在已经清理干净了 - 你可能想要删除那个注释。 - Martin J.
3个回答

6
你可以按照这里的说明使用~/.ssh/config

https://confluence.atlassian.com/pages/viewpage.action?pageId=271943168

Host workdid
 HostName bitbucket.org
 IdentityFile ~/.ssh/workdid
Host personalid
 HostName bitbucket.org
 IdentityFile ~/.ssh/personalid

否则,如果您只想在推送之前“切换帐户”,您可以使用ssh-add。打开Terminal.app,运行ssh-agent并运行ssh-add ~/.ssh/path_to_your_account_id_rsa,然后进行推送。 推送完成后,您可以通过运行ssh-add ~/.ssh/id_rsa切换回默认帐户。
希望对您有所帮助!

1
本博客文章解释了如何很好地使用上述配置:http://dbushell.com/2013/01/27/multiple-accounts-and-ssh-keys/ - ZenBalance

4

另外,如果您通常使用一个默认帐户进行拉取/推送,并且偶尔会向其他帐户推送更改,则可以将引用其他帐户的https URL 添加到您的.git/config文件中,但这样做需要每次输入您的Github密码,并且只有默认的Github帐户(对应启用哪些密钥)将使用ssh密钥。

类似以下内容:

[remote "origin"]
    url = git@github.org:account1/repository.git 
    #This one uses the default ssh keys

[remote "account2"]
    url = https://github.com/account2/repository.git 
    #This will need password while pushing/pulling
[remote "account3"]
    url = https://github.com/account3/repository.git 
    #This will need password while pushing/pulling

对于正常操作,您可以使用SSH密钥进行推送/拉取

git pull origin branch_name
git push origin branch_name

如果要将代码推送到另一个帐户仓库,您可以使用密码通过 https 推送。

git push account2 branch_name
git push account3 branch_name

3
对于BitBucket,我发现最好的方法是a)将密钥添加到~/.ssh/config中,并且b)更改我的项目的本地配置。
例如:
# ~/.ssh/config
Host work
  HostName bitbucket.org
  IdentityFile ~/.ssh/work

Host personal
  HostName bitbucket.org
  IdentityFile ~/.ssh/personal

然后,在我的项目的本地git配置中,我将远程URL的主机部分更改为适当的主机。例如,在以下文件中:

# ~/repos/myworkproject/.git/config
# or you can access this file by going into the repo and running `git config -e`
...snip...
[remote "origin"]
  fetch = ...
  url = git@bitbucket.org:mybitbucketusername/myworkproject.git

将URL行更改为:

url = git@work:mybitbucketusername/myworkproject.git

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接