本文介绍如何正确的在本地电脑上管理多个代码仓库账户并为每个账户配置正确的 SSH 密钥凭据等。

下文中提及的账户均为代码仓库账户(诸如 Github、Gitee、Codeup、Coding 等此类代码仓库平台)的简称。

错误实践

使用 SSH 密钥作代码仓库平台的凭据时,不少人存在以下错误使用方式:

  1. 将本地电脑上生成的 SSH 密钥拷贝到其他电脑上使用,并配置到多个账户中;这导致了密钥的泄漏,存在安全隐患,仅删除本地电脑上的 SSH 密钥无法作废其他电脑上拷贝的密钥
  2. 将本地电脑上生成的单个 SSH 密钥共用于多个账户中;这将导致删除该 SSH 密钥时,其他账户将无法访问代码库。

最佳实践

最佳实践需要满足 SSH 的唯一性:

  1. 针对主机的唯一性:在 A 主机生成的 SSH 密钥仅能在 A 使用,不得拷贝到B、C…等其他主机上,避免密钥泄漏。
  2. 针对账户的唯一性:为每个账户单独生成 SSH 密钥,避免不同账户之间共用 SSH 密钥共享访问权限。

实践步骤

生成密钥

为每个账户生成 SSH 密钥步骤如下:

  1. 生成新的 SSH 密钥:
    1.1 打开终端(Windows 下使用 Git-Bash)
    1.2 运行以下命令以生成新的 SSH 密钥:

    1
    ssh-keygen -t rsa -b 4096 -C "email1@example.com" -f ~/.ssh/id_rsa.email1@example.com
    • email1@example.com替换为与帐户关联的电子邮件。
    • ~/.ssh/id_rsa.email@example.com替换为你想使用的文件路径。
    • 将在私钥同目录下生成.pub后缀的公钥文件,如:id_rsa.email1@example.com.pub
    • 生成过程中的其他输入提示一路回车确认即可。
  2. 拷贝密钥到账户1中,以 Github 为例:
    2.1 将 SSH 公钥复制到剪贴板:clip < ~/.ssh/id_rsa.email1@example.com.pub
    2.2 前往 Github 的账户设置页面下的SSH and GPG keys子页面中添加这个公钥。

  3. 对第二个(或其他)GitHub 帐户重复上述步骤,请务必以不同的方式命名密钥,如,id_rsa.email2)。

配置文件

  1. 编辑配置文件:在文件编辑器中打开~/.ssh/config文件,如果这个文件不存在需要手动创建。

  2. 配置所有账户:参照如下的配置,替换文件路径和用户名为实际值即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # Account 1
    Host github-account1
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa.email1@example.com

    # Account 2
    Host github-account2
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa.email2@example.com
  3. 实际使用示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa1
    PreferredAuthentications publickey
    IdentityAgent none
    IdentitiesOnly yes

    Host codeup.aliyun.com
    HostName codeup.aliyun.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa2
    IdentityAgent none
    IdentitiesOnly yes

    Host codeup.aliyun.com
    HostName codeup.aliyun.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa3
    IdentityAgent none
    IdentitiesOnly yes
  4. 常用配置说明:
    4.1 HostName:填写托管平台服务地址
    4.2 Host:填写别名,方便命令行使用
    4.3 IdentityFile:填写证书位置
    4.4 更多 SSH 配置说明,参见ssh config文档

测试配置

执行如下命令测试配置文件是否正确配置:

1
ssh -T git@github.com

正确配置时将输出以下内容:

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

仓库配置

在每个仓库中,可以单独设置用户名和电子邮件以匹配相应的帐户:

1
2
git config user.name "Your Name"
git config user.email "email@example.com"

也可以全局设置:

1
2
git config --global user.name "Your Default Name"
git config --global user.email "default@example.com"