Skip to main content

GitHub 配置 SSH Key 完整指南

通过配置 SSH Key,你可以安全地连接 GitHub 而无需每次输入用户名和密码。以下是详细配置步骤:

一、检查现有 SSH Key

首先检查是否已存在 SSH Key:

ls -al ~/.ssh

如果看到 id_rsaid_rsa.pub 文件,说明已有 SSH Key。

二、生成新的 SSH Key

  1. 打开终端,输入以下命令(替换为你的GitHub邮箱):
ssh-keygen -t ed25519 -C "your_email@example.com"

或使用传统 RSA 算法:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  1. 提示保存位置时,直接按回车使用默认位置:
> Enter a file in which to save the key (/home/you/.ssh/id_ed25519): [按回车]
  1. 设置安全密码(可选但推荐):
> Enter passphrase (empty for no passphrase): [输入密码]
> Enter same passphrase again: [再次输入密码]

三、将 SSH Key 添加到 ssh-agent

  1. 确保 ssh-agent 正在运行:
eval "$(ssh-agent -s)"
  1. 将 SSH Key 添加到 ssh-agent:
ssh-add ~/.ssh/id_ed25519

四、将 SSH Key 添加到 GitHub 账户

  1. 复制公钥内容:
cat ~/.ssh/id_ed25519.pub
  1. 登录 GitHub,进入:

    • 右上角头像 → Settings → SSH and GPG keys → New SSH key
  2. 填写信息:

    • Title: 标识这个Key的用途(如 "My Work Laptop")
    • Key type: 保持默认 Authentication Key
    • Key: 粘贴刚才复制的公钥内容
  3. 点击 "Add SSH key" 完成添加

五、测试 SSH 连接

验证配置是否成功:

ssh -T git@github.com

第一次连接会看到警告,输入 yes 继续。成功后会显示:

Hi username! You've successfully authenticated...

六、配置 Git 使用 SSH

将现有仓库改为使用 SSH:

git remote set-url origin git@github.com:username/repo.git

或克隆新仓库时直接使用 SSH URL:

git clone git@github.com:username/repo.git

七、多账户配置(可选)

如果有多个GitHub账户,需要额外配置:

  1. 创建第二个SSH Key(使用不同文件名):
ssh-keygen -t ed25519 -C "work_email@company.com" -f ~/.ssh/id_work
  1. 创建/修改 ~/.ssh/config 文件:
# 个人账户
Host github.com-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519

# 工作账户
Host github.com-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_work
  1. 使用特定主机名克隆仓库:
git clone git@github.com-work:company/repo.git

八、常见问题解决

1. 权限问题

确保密钥文件权限正确:

chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

2. 连接被拒绝

检查防火墙设置,确保端口22开放。

3. 提示密码

如果设置了密码但不想每次输入,可添加到钥匙串:

ssh-add --apple-use-keychain ~/.ssh/id_ed25519  # macOS
ssh-add --apple-load-keychain                  # macOS

通过以上步骤,你就可以安全便捷地使用SSH与GitHub交互了。SSH Key比HTTPS更安全,且避免了频繁输入密码的麻烦。