08-git配置多个ssh密钥

81 阅读1分钟

生成 SSH 密钥

  1. 打开终端,进入 ~/.ssh 目录:

    $ cd ~/.ssh
    
  2. 为 GitHub 创建 SSH 密钥:

    $ ssh-keygen -t rsa -C "xxxxxx@163.com" -f ~/.ssh/id_rsa_github
    
    • -t:指定密钥类型,默认是 rsa,可以省略。
    • -C:设置注释文字,比如邮箱。
    • -f:指定密钥文件存储文件名。
  3. 为 GitLab 创建 SSH 密钥:

    $ ssh-keygen -t rsa -C "xxxxxx@163.com" -f ~/.ssh/id_rsa_gitlab
    

添加密钥到 SSH Agent

  1. 添加新的密钥到 SSH agent:
    $ ssh-add id_rsa_github
    $ ssh-add id_rsa_gitlab
    
    如果不使用 ssh-add 指令添加新的密钥到 SSH agent 中,系统会仍然使用 id_rsa 作为默认的 SSH Key,因为 id_rsa 是被默认添加到 SSH agent 中的。

配置 config 文件

config 文件用于配置 SSH 客户端的信息,例如主机名、端口号、用户名、密钥等。对于 Git 代码托管平台,我们可以通过这个配置为不同的 Git 代码托管平台服务器配置不同的 SSH 密钥。

  1. 如果 ~/.ssh 目录下不存在 config 文件,则创建:

    $ touch config
    
  2. 添加配置,在 config 文件中添加以下内容:

    # GitHub 用户
    Host github
    HostName github.com
    User git
    IdentityFile /Users/xxxx/.ssh/id_rsa_github
    
    # GitLab 用户
    Host gitlab
    HostName gitlab.com
    User git
    IdentityFile /Users/xxxx/.ssh/id_rsa_gitlab
    
  3. config 配置介绍:

    • Host:指定连接到的主机名,可以随意指定,相当于实际连接目标主机的别名。
    • HostName:指定连接到的主机的实际域名或IP地址。如果是向 GitHub 推送代码,则为 github.com,如果是向公司的 Git 代码托管平台推送代码,则填写公司主机的地址。
    • User:指定使用的用户名,通常为 git
    • Port:SSH 服务的端口号,默认为 22,可以省略。
    • PreferredAuthentications:指定优先使用的身份验证方法,指定为 publickey,即使用公钥进行身份认证。
    • IdentityFile:指定要使用的私钥文件路径。

在 GitHub 和 GitLab 网站添加 SSH 公钥

  1. 查看 GitHub 公钥:

    $ cat id_rsa_github.pub
    
  2. 查看 GitLab 公钥:

    $ cat id_rsa_gitlab.pub
    

测试连接

  1. 测试 GitHub 连接:

    $ ssh -T git@github.com
    
  2. 测试 GitLab 连接:

    $ ssh -T git@gitlab.com
    

参考文章:
Mac上配置SSH
如何配置 SSH 管理多个 Git 仓库和以及多个 Github 账号
git 多账号 ssh-key 管理

git系列文章

01-git常用命令汇总

02-git config介绍

03-git工作区、暂存区、版本库介绍

04-git log命令介绍

05-git关联远程仓库

06-git分支管理策略

07-git合并冲突

07-git合并冲突场景

08-git配置多个ssh密钥