一、什么是 SSH 密钥?
SSH(Secure Shell)密钥是一种用于在计算机和 GitHub 之间建立安全连接的加密方法。配置 SSH 密钥后,可以通过 SSH 协议访问 GitHub 仓库,而无需输入用户名和密码。
二、生成并配置 SSH 密钥的流程
1. 检查现有的 SSH 密钥
- 打开 终端。
-
检查默认位置是否已有 SSH 密钥:
ls -al ~/.ssh
- 常见的 SSH 密钥文件名:
id_rsa
和id_rsa.pub
(默认密钥)。id_ed25519
和id_ed25519.pub
(推荐的现代密钥)。
- 常见的 SSH 密钥文件名:
-
如果已存在密钥,可直接跳到 步骤 4 绑定到 GitHub。
2. 生成新的 SSH 密钥
-
在终端中运行以下命令:
ssh-keygen -t ed25519 -C "your_email@example.com"
- 选项解释:
-t ed25519
:生成 Ed25519 类型密钥(推荐,速度更快且安全)。-C "your_email@example.com"
:使用 GitHub 注册邮箱作为备注。
- 选项解释:
-
出现提示时:
-
文件保存路径:
- 按
Enter
使用默认路径(~/.ssh/id_ed25519
)。 - 或输入自定义路径。
- 按
-
设置密码:
- 可选择设置密钥密码,也可直接按
Enter
留空。
- 可选择设置密钥密码,也可直接按
-
3. 添加 SSH 密钥到 SSH Agent
- 启动 SSH Agent:
eval "$(ssh-agent -s)"
- 添加新生成的 SSH 密钥到 Agent:
如果使用了自定义路径,请替换为实际路径。ssh-add ~/.ssh/id_ed25519
4. 将 SSH 公钥绑定到 GitHub
-
显示公钥内容:
cat ~/.ssh/id_ed25519.pub
复制终端输出的完整公钥。
-
打开 GitHub 账户设置:
- 登录 GitHub 官网。
- 点击右上角头像,选择 Settings。
-
导航到 SSH 密钥设置:
- 在左侧菜单选择 SSH and GPG keys。
- 点击 New SSH key。
-
添加公钥:
- Title:填写密钥名称(如
MacBook SSH Key
)。 - Key:粘贴复制的公钥内容。
- 点击 Add SSH key。
- Title:填写密钥名称(如
5. 测试连接
-
在终端中运行以下命令测试连接:
ssh -T git@github.com
可能会出现提示确认连接,输入
yes
并按回车。 -
如果配置正确,输出类似以下内容:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
6. 配置多个 GitHub 账户(可选)
如果需要在同一设备上使用多个 GitHub 账户:
-
创建额外的 SSH 密钥:
ssh-keygen -t ed25519 -C "your_other_email@example.com" -f ~/.ssh/id_ed25519_other
-
配置 SSH 配置文件:
- 编辑或创建
~/.ssh/config
文件:nano ~/.ssh/config
-
添加以下内容:
Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519 Host github-other HostName github.com User git IdentityFile ~/.ssh/id_ed25519_other
- 保存并退出。
- 编辑或创建
-
使用特定账户克隆仓库:
git clone git@github-other:username/repository.git
三、常见问题与解决方法
1. SSH 连接失败
现象:
- 测试连接时提示
Permission denied (publickey)
。解决方法:
- 确保正确绑定公钥到 GitHub。
- 检查是否正确添加私钥到 SSH Agent:
ssh-add -l
- 确保 Git 使用 SSH URL:
git remote set-url origin git@github.com:username/repository.git
2. 提示密钥密码
现象:
- 每次使用密钥时需输入密码。
解决方法:
- 启用 macOS Keychain 集成:
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
四、参考资料