配置 GitHub 的 SSH Key 是连接本地开发环境与远程仓库的重要步骤,以下是详细的配置流程:
一、检查现有 SSH Keys
首先确认本地是否已有 SSH Key:
ls -al ~/.ssh
# 可能的输出:id_rsa.pub、id_ed25519.pub 等(.pub 后缀为公钥)
- 若有密钥且希望复用,直接跳到 步骤四。
- 若无密钥或需生成新密钥,继续下一步。
二、生成新的 SSH Key
使用 ssh-keygen
命令生成密钥对(推荐使用 ed25519
算法):
ssh-keygen -t ed25519 -C "your_email@example.com"
- 提示保存位置时,直接回车(默认路径为
~/.ssh/id_ed25519
)。 - 设置密码时,可留空(无密码更方便,但安全性稍低)。
三、启动 SSH Agent 并添加密钥
-
启动 SSH Agent:
eval "$(ssh-agent -s)" # 输出示例:Agent pid 59566
-
添加私钥到 Agent:
ssh-add ~/.ssh/id_ed25519
四、复制公钥到剪贴板
# macOS/Linux
pbcopy < ~/.ssh/id_ed25519.pub # macOS
xclip -sel clip < ~/.ssh/id_ed25519.pub # Linux (需安装 xclip)
# Windows (Git Bash)
cat ~/.ssh/id_ed25519.pub | clip
五、在 GitHub 中添加 SSH Key
- 登录 GitHub,点击右上角头像 → Settings → SSH and GPG keys。
- 点击 New SSH key 或 Add SSH key。
- Title:填写标识(如
MacBook Pro
)。 - Key:粘贴刚才复制的公钥内容(以
ssh-ed25519
开头)。 - 点击 Add SSH key,输入 GitHub 密码确认。
六、验证连接
ssh -T git@github.com
- 首次连接会提示确认指纹,输入
yes
继续。 - 成功信息:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
七、常见问题
1. 连接失败:Permission denied (publickey)
- 检查密钥是否添加到 GitHub:确认公钥已正确粘贴到 GitHub。
- 检查 Agent 是否加载密钥:
ssh-add -l # 查看已加载的密钥
2. 提示 "Could not open a connection to your authentication agent"
- 重新启动 Agent:
eval "$(ssh-agent -s)"
3. 多个 GitHub 账号的 SSH 配置
编辑 ~/.ssh/config
文件,添加主机别名:
# 默认 GitHub 账号
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
# 第二个 GitHub 账号
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_work
使用时,仓库 URL 需改为:
git clone git@github-work:username/repo.git
八、后续操作
配置完成后,可使用 SSH 协议克隆仓库:
git clone git@github.com:username/repo.git
通过 SSH 连接,无需每次输入用户名和密码,且传输更安全。