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



我在github/bitbucket上有多个帐户,每个帐户都有一个唯一的私钥对。当我需要推送到不同帐户创建的存储库时,就会出现问题,除非我推送到默认帐户(我最初创建的帐户),否则我几乎肯定会被拒绝访问。

有没有办法在推送之前切换到不同的凭据?我在Macintosh机器上使用源代码树。我宁愿在需要推送时不要手动重命名~/.ssh/id_rsa

非常感谢您的投入!

您可以使用

~/.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

希望对您有所帮助!

另一方面,如果您通常使用一个默认帐户来拉取/推送,并且您偶尔会将更改推送到其他帐户,则可以将引用其他帐户的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

对于 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 = git@work:mybitbucketusername/myworkproject.git

相关内容

最新更新