如何实现为不同的 git 托管服务器提供不同的 ssh key呢?

如何实现在 Windows 11 上为 GitHub 生成新的 SSH 密钥而不覆盖现有密钥呢?

🛠️ 步骤 1:检查现有 SSH 密钥

打开 Git Bash ,输入以下命令查看现有的 SSH 密钥:

ls ~/.ssh

如果看到类似 id_rsaid_ed25519 的文件,说明已有密钥存在。


🛠️ 步骤 2:生成新的 SSH 密钥

使用以下命令生成新的 SSH 密钥,并为其指定一个不同的文件名,以避免覆盖现有密钥:

ssh-keygen -t ed25519 -C "your_email@example.com" -f ~/.ssh/id_ed25519_github

此命令将创建名为 id_ed25519_github 的私钥和 id_ed25519_github.pub 的公钥。

请注意:

  1. 请务必将示例中的 “your_email@example.com” 改为你自己的邮箱
  2. “id_ed25519_github” 可以自定义,但请确保之后的操作也一并同步修改

🛠️ 步骤 3:添加新密钥到 SSH Agent

确保 SSH Agent 正在运行,并将新生成的密钥添加到其中:

# 启动 SSH Agent
eval "$(ssh-agent -s)"

# 添加新密钥
ssh-add ~/.ssh/id_ed25519_github


🛠️ 步骤 4:配置 SSH 使用指定的密钥

编辑或创建 ~/.ssh/config 文件,添加以下内容,以指定在连接 GitHub 时使用新生成的密钥:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_github
  IdentitiesOnly yes

保存并关闭该文件。


🛠️ 步骤 5:将公钥添加到 GitHub

  1. 复制公钥内容:

    cat ~/.ssh/id_ed25519_github.pub
    
    

    将输出的内容复制到剪贴板。

  2. 登录到你的 GitHub 账户,并访问:https://github.com/settings/keys

  3. 按图示操作粘贴之前复制的公钥内容保存即可。



✅ 完成

现在,你已经成功为 GitHub 创建了一个新的 SSH 密钥,并配置了系统以在连接 GitHub 时使用该密钥。


如果你需要为多个 GitHub 账户配置不同的 SSH 密钥,或者在多个项目中使用不同的密钥,可以在 ~/.ssh/config 文件中添加多个 Host 条目。例如:

# 个人账户
Host github.com-personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_personal
  IdentitiesOnly yes

# 工作账户
Host github.com-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work
  IdentitiesOnly yes

然后,在克隆仓库时,使用对应的主机别名:

git clone [email protected]:username/repo.git

这样可以根据不同的账户使用不同的 SSH 密钥。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容