通过 SSH 配置管理多密钥共存

181 阅读2分钟

你可以为 GitHub 单独生成新密钥,并通过 SSH 配置管理多密钥共存。以下是完整操作步骤:


1. 生成新的 GitHub 专属密钥

# 打开终端(Git Bash/PowerShell)
ssh-keygen -t ed25519 -C "your_github_email@example.com"
  • 当提示保存路径时,修改默认路径避免覆盖现有 GitLab 密钥:
    Enter file in which to save the key (C:\Users\chenwa2/.ssh/id_ed25519): 
    ➜ 输入新路径(例如):`C:\Users\chenwa2\ssh\github_id_ed25519`
    
  • 按需设置密码(直接回车留空则无密码)

2. 查看生成的新密钥

生成后你会得到两个文件:

  • 私钥C:\Users\chenwa2\ssh\github_id_ed25519
  • 公钥C:\Users\chenwa2\ssh\github_id_ed25519.pub

3. 添加新公钥到 GitHub

  1. 复制公钥内容

    cat C:\Users\chenwa2\ssh\github_id_ed25519.pub
    
    • 内容以 ssh-ed25519 AAA... 开头,完整复制
  2. 添加到 GitHub

    • 登录 GitHub → Settings → SSH and GPG keys → New SSH key
    • Title:My GitHub Key(自定义名称)
    • Key:粘贴复制的公钥内容

4. 配置 SSH 多密钥管理

C:\Users\chenwa2\.ssh 目录下创建/修改 config 文件:
(没有后缀名,可用 VS Code 或 Notepad++ 编辑)

# GitLab 配置(使用原有密钥)
Host gitlab.com
  HostName gitlab.com
  User git
  IdentityFile C:\Users\chenwa2\ssh\id_ed25519
  IdentitiesOnly yes

# GitHub 配置(使用新密钥)
Host github.com
  HostName github.com
  User git
  IdentityFile C:\Users\chenwa2\ssh\github_id_ed25519
  IdentitiesOnly yes

5. 测试 GitHub 连接

ssh -T git@github.com
  • 预期输出:
    Hi your_github_username! You've successfully authenticated...

6. 使用新密钥克隆/关联仓库

  • 新仓库克隆

    git clone git@github.com:用户名/仓库名.git
    
  • 修改现有仓库远程地址(如果之前用 HTTPS):

    git remote set-url origin git@github.com:用户名/仓库名.git
    

关键注意事项

  1. 密钥共存

    • GitLab 继续使用原有密钥 id_ed25519
    • GitHub 使用新密钥 github_id_ed25519
  2. 路径分隔符

    • Windows 路径需使用双反斜杠或正斜杠(示例中已适配)
  3. 权限问题

    • 确保私钥文件权限安全(非公开可读):
      icacls C:\Users\chenwa2\ssh\github_id_ed25519 /inheritance:r
      icacls C:\Users\chenwa2\ssh\github_id_ed25519 /grant:r "%USERNAME%":"R"
      

完成以上步骤后,你即可同时安全地使用:

  • 旧密钥操作 GitLab 仓库
  • 新密钥操作 GitHub 仓库