主题
GitHub SSH 密钥配置指南
概述
通过 SSH(Secure Shell Protocol)协议连接 GitHub,可以在不安全网络中建立安全通道,实现代码仓库的读写操作。
前置要求
- Git 已安装
- 终端或命令行工具
- GitHub 账户
检查现有 SSH 密钥
在生成新密钥之前,检查系统是否已存在 SSH 密钥。
操作步骤
- 打开终端
- 输入以下命令查看是否存在 SSH 密钥:
bash
ls -al ~/.ssh- 检查输出结果中是否存在以下文件:
id_rsa.pubid_ecdsa.pubid_ed25519.pub
如果存在以上任意文件,表示已有 SSH 密钥,可直接用于 GitHub 配置。如需新建密钥,请继续下一步。
生成新的 SSH 密钥
操作步骤
- 打开终端
- 粘贴以下命令,将邮箱地址替换为 GitHub 账户邮箱:
bash
ssh-keygen -t ed25519 -C "your_email@example.com"注意:对于不支持 Ed25519 算法的旧系统,使用以下命令:
bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"- 当提示 "Enter a file in which to save the key" 时,按 Enter 键使用默认路径
- 输入安全密码(可选,按 Enter 跳过)
bash
> Enter passphrase (empty for no passphrase): [输入密码]
> Enter same passphrase again: [再次输入密码]启动 SSH Agent 并添加密钥
macOS
bash
# 启动 ssh-agent
eval "$(ssh-agent -s)"
# 添加私钥到 ssh-agent
ssh-add --apple-use-keychain ~/.ssh/id_ed25519Linux
bash
# 启动 ssh-agent
eval "$(ssh-agent -s)"
# 添加私钥到 ssh-agent
ssh-add ~/.ssh/id_ed25519Windows(Git Bash)
bash
# 启动 ssh-agent
eval "$(ssh-agent -s)"
# 添加私钥到 ssh-agent
ssh-add ~/.ssh/id_ed25519将 SSH 公钥添加到 GitHub 账户
复制公钥内容
macOS:
bash
pbcopy < ~/.ssh/id_ed25519.pubWindows(Git Bash):
bash
clip < ~/.ssh/id_ed25519.pubLinux:
bash
cat ~/.ssh/id_ed25519.pub
# 手动复制输出内容添加到 GitHub
- 登录 GitHub
- 点击右上角头像,选择 Settings
- 在左侧边栏 "Access" 部分,点击 SSH and GPG keys
- 点击 New SSH key 或 Add SSH key
- 在 "Title" 字段填写描述性标签(如 "Personal Laptop")
- 选择密钥类型:Authentication
- 在 "Key" 字段粘贴公钥内容
- 点击 Add SSH key
- 如有提示,确认 GitHub 账户访问权限
测试 SSH 连接
完成配置后,测试 SSH 连接是否正常。
操作步骤
- 打开终端
- 输入以下命令:
bash
ssh -T git@github.com- 首次连接会提示验证 GitHub 的真实性:
bash
> The authenticity of host 'github.com (IP ADDRESS)' can't be established.
> ED25519 key fingerprint is SHA256:xxxxx.
> Are you sure you want to continue connecting (yes/no)?输入
yes继续成功连接后将显示:
bash
> Hi username! You've successfully authenticated, but GitHub does not provide shell access.使用 SSH 方式克隆仓库
配置完成后,使用 SSH URL 克隆仓库。
克隆命令
bash
git clone git@github.com:USERNAME/REPOSITORY.git将 USERNAME 替换为 GitHub 用户名,REPOSITORY 替换为仓库名称。
切换现有仓库的远程 URL
如果已使用 HTTPS 方式克隆仓库,可切换为 SSH 方式:
- 查看当前远程 URL:
bash
git remote -v- 修改远程 URL 为 SSH:
bash
git remote set-url origin git@github.com:USERNAME/REPOSITORY.git- 验证修改:
bash
git remote -v
# 输出应显示:
# origin git@github.com:USERNAME/REPOSITORY.git (fetch)
# origin git@github.com:USERNAME/REPOSITORY.git (push)密钥类型说明
GitHub 支持以下 SSH 密钥类型:
| 密钥类型 | 说明 |
|---|---|
| Ed25519 | 推荐使用,安全性高且性能优越 |
| RSA (4096位) | 兼容性好,适用于旧系统 |
| ECDSA | 替代方案 |
| DSA | 已弃用,GitHub 于 2022年3月15日 停止支持 |
常见问题
Permission denied (publickey)
原因:SSH 密钥未正确添加到 ssh-agent 或 GitHub 账户
解决方案:
- 确认 ssh-agent 正在运行
- 确认密钥已添加到 ssh-agent
- 确认公钥已添加到 GitHub 账户
Host key verification failed
原因:首次连接 GitHub 时未确认主机密钥
解决方案: 手动将 GitHub 添加到已知主机:
bash
ssh-keyscan github.com >> ~/.ssh/known_hosts使用 HTTPS 端口绕过防火墙
如果网络限制 SSH 协议(端口 22),可配置 SSH 通过 HTTPS 端口(443)连接:
- 编辑 SSH 配置文件:
bash
nano ~/.ssh/config- 添加以下内容:
text
Host github.com
Hostname ssh.github.com
Port 443
User git保存并退出
测试连接:
bash
ssh -T git@github.com