如何将单个本地Git仓库推送到两个不同的GitHub账户
解决单本地Git仓库向两个GitHub账户推送/拉取的权限问题
核心问题分析
你当前配置的远程仓库URL直接使用git@github.com格式,没有匹配~/.ssh/config里定义的Host别名,导致SSH无法自动选择对应账户的密钥,从而触发权限拒绝错误。
修复步骤
1. 重新配置远程仓库URL
删除现有远程,改用~/.ssh/config中定义的Host别名来设置远程地址:
# 删除原有远程 git remote remove myremote1 git remote remove myremote2 # 重新添加远程,格式为 [Host别名]:[GitHub用户名]/[仓库名].git git remote add myremote1 github-user1:github-user1/myproject.git git remote add myremote2 github-user2:github-user2/myproject.git
执行git remote -v验证,正确输出应为:
myremote1 github-user1:github-user1/myproject.git (fetch) myremote1 github-user1:github-user1/myproject.git (push) myremote2 github-user2:github-user2/myproject.git (fetch) myremote2 github-user2:github-user2/myproject.git (push)
2. 修正SSH密钥添加操作
你之前重复添加了github-user1的密钥,漏掉了github-user2的,重新执行以下命令:
# 启动ssh-agent eval "$(ssh-agent -s)" # 添加两个账户的密钥 ssh-add ~/.ssh/id_ed25519_github_user1 ssh-add ~/.ssh/id_ed25519_github_user2
用ssh-add -l命令可查看已加载的密钥列表,确认两个密钥都已成功添加。
3. 验证SSH连接有效性
分别测试两个账户的SSH连接,确保密钥和配置生效:
ssh -T github-user1 ssh -T github-user2
成功的话会收到GitHub的认证提示,类似:Hi github-user1! You've successfully authenticated, but GitHub does not provide shell access.
4. 可选:配置本地仓库提交用户信息(避免作者混乱)
如果需要区分不同账户的提交作者,可在本地仓库根目录设置默认提交信息:
# 设置默认使用github-user1的信息 git config user.name "github-user1" git config user.email "github-user1@gmail.com"
临时需要用github-user2提交时,可在commit时指定:
git commit --author="github-user2 <github-user2@gmail.com>" -m "你的提交信息"
额外注意事项
- 确保Windows下的
~/.ssh/config文件路径为C:\Users\[你的用户名]\.ssh\config,且文件无后缀名(不要是config.txt)。 - 确认两个账户的公钥已正确添加到对应GitHub账户的SSH Keys列表中。
内容的提问来源于stack exchange,提问作者freenrg
相关产品推荐
相关产品推荐

