文章

生成与配置多个密钥

生成与配置多个密钥

在 GitHub 上配置 SSH Key

步骤 1:生成新的 SSH Key

如果没有密钥,执行以下命令生成(替换为你的 GitHub 注册邮箱):

ssh-keygen -t ed25519 -C "your_email@example.com"
  • ed25519 是推荐的加密算法,更安全;如果系统不支持,可改用 rsassh-keygen -t rsa -b 4096 -C "your_email@example.com"

执行后会出现提示:

  1. 询问密钥保存路径(默认 ~/.ssh/id_ed25519),直接按回车使用默认路径。
  2. 询问是否设置密码(可选,设置后每次使用 SSH 时需要输入密码,更安全),直接按回车跳过(无密码)。

生成成功后,~/.ssh 目录下会新增两个文件:

  • id_ed25519:私钥(绝对不能泄露)。
  • id_ed25519.pub:公钥(需要上传到 GitHub)。

步骤 2:复制公钥内容

需要将公钥(id_ed25519.pubid_rsa.pub)的内容复制到剪贴板。

步骤 3:在 GitHub 上添加 SSH Key

  1. 登录 GitHub,点击右上角头像 → Settings(设置)。
  2. 在左侧菜单找到 SSH and GPG keys → 点击右上角 New SSH key
  3. 在表单中:
    1. Title:自定义名称(如“我的笔记本”,方便区分不同设备)。
    2. Key:粘贴刚才复制的公钥内容(确保没有多余空格或换行)。
  4. 点击 Add SSH key,可能需要输入 GitHub 密码或验证二次身份。

步骤 4:验证配置是否成功

终端执行以下命令,测试是否能通过 SSH 连接 GitHub:

ssh -T git@github.com

首次连接会提示是否信任主机,输入 yes 并回车。如果成功,会显示类似信息(包含你的用户名):

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

如果失败,检查公钥是否复制正确、GitHub 上的 Key 是否添加成功,或重新生成密钥重试。

配置 SSH 客户端

为了让 SSH 客户端知道使用哪个密钥连接到哪个主机,需要编辑 ~/.ssh/config 文件:

  1. 创建或编辑 ~/.ssh/config

    1
    2
    
    touch ~/.ssh/config
    chmod 600 ~/.ssh/config  # 确保权限正确
    
  2. 添加配置: 编辑 ~/.ssh/config,添加如下内容:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    # GitHub
    Host github.com
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_ed25519_github
        IdentitiesOnly yes
       
    # GitLab
    Host gitlab.com
        HostName gitlab.com
        User git
        IdentityFile ~/.ssh/id_ed25519_gitlab
        IdentitiesOnly yes
    
    • Host:定义一个别名(可以自定义,如 githubgitlab
    • HostName:实际的主机名
    • User:通常是 git(Git 服务的默认用户)
    • IdentityFile:指定使用的私钥文件
    • IdentitiesOnly yes:强制只使用指定的密钥,避免 SSH 尝试其他密钥

    注意:Windows 系统中,需要将路径修改为 Windows 格式,例如:C:/Users/用户名/.ssh/id_ed25519_github

  3. 使用别名简化配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    # 个人GitHub账号
    Host github-personal
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_ed25519_github_personal
        IdentitiesOnly yes
       
    # 工作GitHub账号
    Host github-work
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_ed25519_github_work
        IdentitiesOnly yes
    

    使用此配置后,克隆仓库时需要这样使用:

    1
    2
    3
    4
    5
    
    # 个人账号
    git clone git@github-personal:username/repo.git
       
    # 工作账号
    git clone git@github-work:company/repo.git
    
本文由作者按照 CC BY 4.0 进行授权