AI模型:Deepseek
仅供参考。
第一步:生成 SSH 密钥对
在终端(Windows 推荐用 Git Bash 或 PowerShell)中运行:
```bash
ssh-keygen -t ed25519 -C "your_email@example.com"
```
> 将 `your_email@example.com` 替换为你的 GitHub 注册邮箱。
然后按提示操作:
-
保存路径:直接回车,使用默认路径 `~/.ssh/id_ed25519`
-
密码短语:可选但推荐设置,为私钥多加一层保护
-
若 `ed25519` 算法不可用(如系统过旧),可改用 RSA:`ssh-keygen -t rsa -b 4096 -C "your_email@example.com"`
密钥文件说明:
| 文件名 | 用途 |
|--||
| `~/.ssh/id_ed25519` | 私钥 --- 留在本地,⚠️ 绝对不要分享给任何人 |
| `~/.ssh/id_ed25519.pub` | 公钥 --- 需要添加到 GitHub |
第二步:添加到 ssh-agent(可选)
启动 SSH 代理并将私钥添加进去:
```bash
eval "$(ssh-agent -s)" # 启动 ssh-agent
ssh-add ~/.ssh/id_ed25519 # 添加私钥
```
这样可以在当前会话中重用密钥,避免重复输入密码。
第三步:将公钥添加到 GitHub
1. 复制公钥
-
macOS:`pbcopy < ~/.ssh/id_ed25519.pub`
-
Linux(需装 xclip):`xclip -selection clipboard < ~/.ssh/id_ed25519.pub`
-
Windows Git Bash:`cat ~/.ssh/id_ed25519.pub | clip`
-
通用方法:`cat ~/.ssh/id_ed25519.pub`,然后手动选中并复制所有输出
2. 登录 GitHub 添加
-
登录 GitHub,点击右上角头像 → Settings
-
左侧边栏点击 SSH and GPG keys
-
点击 New SSH key 按钮
-
填写信息:
-
Title:填写一个便于识别的名称(如 "My MacBook Pro" 或 "Office Desktop")
-
Key type:保持默认的 "Authentication Key"
-
Key:粘贴刚刚复制的公钥内容
- 点击 Add SSH key,按要求确认密码
第四步:测试连接
在终端中运行:
```bash
ssh -T git@github.com
```
首次连接会提示确认 host key,输入 `yes` 继续。看到如下输出即表示成功:
```
Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.
```
如果看到权限拒绝(Permission denied)错误,请检查公钥是否完整粘贴、邮箱是否正确。
第五步:使用 SSH 协议操作仓库
配置完成后,即可使用 `git@github.com:` 格式的地址:
- 克隆新仓库:
```bash
git clone git@github.com:用户名/仓库名.git
示例:git clone git@github.com:octocat/Hello-World.git
```
SSH 地址可从仓库页面点击 "Code" → "SSH" 获取
- 修改既有仓库(将 HTTPS 地址改为 SSH):
```bash
git remote set-url origin git@github.com:用户名/仓库名.git
```
之后 `git push`、`git pull` 就不再需要每次输入密码了。
常见问题排查
| 现象 | 解决方法 |
||-|
| `ssh-add` 报 "Could not open a connection" | 先执行 `eval "$(ssh-agent -s)"` 启动代理 |
| 公司网络封锁 22 端口 | 改用 443 端口:`ssh -T -p 443 git@ssh.github.com` |
| Windows 环境没有 `ssh-keygen` | 安装 [Git for Windows](https://git-scm.com/downloads/win),使用 Git Bash |
> 💡 小建议:一台设备配一个密钥就够了,如果换新电脑重新走一遍流程即可。不再用的旧设备记得去 GitHub 删掉对应的密钥,避免留下安全隐患。