多Github账号管理使用

109 阅读2分钟

🎯 场景目标:

你有两个 GitHub 账号:

  • ✅ A账号:用于 VS Code 登录和 GitHub Copilot
  • ✅ B账号:用于 Git 操作(推送代码)

你希望项目 A 推送到账号 B 的 GitHub 仓库中,不冲突。

🧱 核心原理:

Git 通过 SSH key 或 HTTPS token 验证身份。

我们通过以下方法让不同的 GitHub 项目使用不同 SSH key,这样就能对应不同 GitHub 账号。

✅ 步骤详解

🔹 1. 为第二个账号生成 SSH Key

默认的 SSH key 是 ~/.ssh/id_rsa,我们要为第二个 GitHub 账号生成一个新的 key。

ssh-keygen -t rsa -C "your-second-email@example.com"
# 出现提示时输入保存路径:
# 建议命名为 ~/.ssh/id_rsa_work 或 ~/.ssh/id_rsa_personal 等

# 示例输入路径:
# > Enter file in which to save the key: /home/yourname/.ssh/id_rsa_work

这样会生成两个文件:

  • ~/.ssh/id_rsa_work(私钥)
  • ~/.ssh/id_rsa_work.pub(公钥)

🔹 2. 添加公钥到 GitHub(账号 B)

  1. 登录你要用来 推送代码的 GitHub 账号(账号 B)
  2. 进入页面:github.com/settings/ke…
  3. 点 “New SSH key”
  4. ~/.ssh/id_rsa_work.pub 文件内容复制粘贴进去

🔹 3. 配置 SSH 区分两个 GitHub 账号

编辑你的 SSH 配置文件:

code ~/.ssh/config

添加以下内容(如果没有文件,就新建):

# GitHub Copilot / 主账号默认设置
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

# GitHub 推送代码使用的账号
Host github-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_work

注意 IdentityFile 要写你实际保存私钥的完整路径

现在你就可以通过 github-work 来识别你第二个账号的 SSH。

🔹 4. 修改 Git 项目使用的远程地址

  1. 进入你要推送到账号 B 的项目目录:
cd ~/projects/my-other-project
  1. 替换项目的远程地址(使用自定义 host)
# 原远程地址可能是:
# git@github.com:your-username/repo.git

# 替换为:
git remote set-url origin git@github-work:your-username/repo.git

注意这里的 github-work: 是你在 ~/.ssh/config 中写的 Host 别名,不是 GitHub 上的用户名。

🔹 5. 验证是否成功

# 测试连接是否使用了正确账号
ssh -T git@github-work

你应该会看到:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

若有问题,执行

ssh -vT git@github-xxx

如果 config 正确,应该会看到 github.com 的连接日志

几个注意点

为避免出现路径问题,建议

  • 直接在.ssh路径下打开终端 image.png
  • config文件路径必须是xxxx\.ssh\config,注意没有文件扩展名
  • config文件内容必须是如下格式,不能有中文标点和多余空格,保存文件为UTF-8 无 BOM 格式(用 VSCode 或 Notepad++ 打开 config 文件,另存为 UTF-8(无 BOM))
Host github-xxx
    HostName github.com
    User git
    IdentityFile xxx.ssh/id_rsa_xxx

Tip: image.png 若遇到以上报错,99%是 config 文件格式或编码问题,或者文件名带了隐藏扩展名

文件路径及config文件内容参考如下:

image.png

image.png

注意远程地址问题:

image.png