You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git推送遇403权限拒绝:如何切换账号实现多账号推送?

Git多账号切换与403权限错误解决方法

问题场景

推送代码时持续触发403权限错误:

> git push
remote: Permission to <ACCOUNT_2>/<REPO>.git denied to <ACCOUNT_1>.
fatal: unable to access 'https://github.com/<ACCOUNT_2>/<REPO>.git/': The requested URL returned error: 403

已在VS Code中配置<ACCOUNT_2>的用户名和邮箱,但推送时仍识别为<ACCOUNT_1>,需要频繁切换Git账号,寻求更高效的解决方案。

Git操作日志:

2023-08-11 18:21:50.006 [info] > git log --oneline --cherry main...main@{upstream} -- [45ms]
2023-08-11 18:21:50.712 [info] > git pull --tags origin main [702ms]
2023-08-11 18:21:50.712 [info] From https://github.com/<ACCOUNT_2>/<REPO>
 * branch            main       -> FETCH_HEAD
2023-08-11 18:21:51.674 [info] > git push origin main:main [959ms]
2023-08-11 18:21:51.674 [info] remote: Permission to <ACCOUNT_2>/<REPO>.git denied to <ACCOUNT_1>.
fatal: unable to access 'https://github.com/<ACCOUNT_2>/<REPO>.git/': The requested URL returned error: 403

高效切换Git账号的方法

1. 仓库级单独配置账号

针对单个仓库设置专属账号,无需修改全局配置:

  • 进入目标仓库目录,执行:
    git config user.name "<ACCOUNT_2>"
    git config user.email "<ACCOUNT_2_EMAIL>"
    
    该仓库会优先使用本地配置,覆盖全局设置。

2. 使用SSH密钥区分账号

通过独立SSH密钥绑定不同账号,实现自动匹配:

  • 为每个账号生成独立SSH密钥:
    ssh-keygen -t ed25519 -C "<ACCOUNT_1_EMAIL>"  # 保存为~/.ssh/id_ed25519_account1
    ssh-keygen -t ed25519 -C "<ACCOUNT_2_EMAIL>"  # 保存为~/.ssh/id_ed25519_account2
    
  • 在~/.ssh/config中添加映射配置:
    Host github.com-account1
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_account1
    
    Host github.com-account2
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_account2
    
  • 修改仓库远程地址为对应SSH格式:
    git remote set-url origin git@github.com-account2:<ACCOUNT_2>/<REPO>.git
    
    后续操作会自动匹配对应密钥,无需手动切换账号。

3. 清除凭据缓存

系统或Git缓存的旧账号凭据会导致新配置不生效,需手动清除:

  • Windows:打开「凭据管理器」→「Windows凭据」,删除Git相关条目,重新推送时输入新账号信息。
  • Mac:终端执行:
    security delete-generic-password -l "github.com"
    
  • Linux:执行以下命令临时禁用缓存,下次推送重新输入账号:
    git config --global credential.helper cache --timeout 0
    

4. VS Code内置账号切换

利用VS Code的多账号管理功能直接切换:

  • 点击左下角当前账号头像,选择「添加账号」登录<ACCOUNT_2>。
  • 打开目标仓库后,在左下角头像处切换到<ACCOUNT_2>,再执行推送操作。

内容的提问来源于stack exchange,提问作者M7ilan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:15:35