(2025 年 4 月更新版)
一、为什么需要 SSH 密钥?
- 免密登录:无需每次输入密码即可推送 / 拉取代码
- 安全验证:通过非对称加密技术保障通信安全
- 多平台支持:适用于 GitHub/GitLab/Bitbucket 等主流平台
二、配置步骤详解
1. 检查现有密钥
bash
ls -al ~/.ssh # macOS/Linux 系统
dir %USERPROFILE%\.ssh # Windows 系统
常见密钥文件:
id_rsa.pub
(RSA 算法)id_ed25519.pub
(推荐的 ED25519 算法)authorized_keys
(已授权的公钥列表)
💡 提示:若已存在密钥但需要更新,可跳过此步骤直接生成新密钥。
2. 生成新 SSH 密钥
bash
# 推荐使用 ED25519 算法(安全性更高)
ssh-keygen -t ed25519 -C "your_email@example.com"
# 若需兼容旧系统,可使用 RSA 算法(2048位及以上)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
交互说明:
- 保存路径:直接回车使用默认路径(
~/.ssh/id_ed25519
) - 密码设置:
- 建议设置强密码(推荐)
- 若需免密登录,可留空(安全性降低)
3. 启动 SSH 代理(守护进程)
bash
# macOS/Linux 系统
eval "$(ssh-agent -s)"
# Windows 系统(PowerShell)
Start-Service ssh-agent
4. 添加密钥到代理
bash
# 默认密钥路径
ssh-add ~/.ssh/id_ed25519
# 若密钥路径不同,需指定路径
ssh-add /path/to/your/private_key
❗ 注意:若添加失败,可能需要先修改密钥文件权限:
bash
chmod 600 ~/.ssh/id_ed25519
5. 绑定公钥到 Git 平台
复制公钥内容:
bash
# macOS 系统
pbcopy < ~/.ssh/id_ed25519.pub
# Linux 系统
xclip -sel clip < ~/.ssh/id_ed25519.pub
# Windows 系统(PowerShell)
Get-Content ~/.ssh/id_ed25519.pub | Set-Clipboard
绑定流程(以 GitHub 为例):
- 登录 GitHub → Settings → SSH and GPG keys
- 点击 "New SSH key"
- 粘贴公钥内容 → 命名 → 保存
6. 验证连接
bash
# GitHub 验证命令
ssh -T git@github.com
# GitLab 验证命令
ssh -T git@gitlab.com
成功提示:
plaintext
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
三、高级配置技巧
-
多账户管理:
- 创建多个密钥对(如
id_github
、id_gitlab
) - 配置
~/.ssh/config
文件:plaintext
Host github.com IdentityFile ~/.ssh/id_github Host gitlab.com IdentityFile ~/.ssh/id_gitlab
- 创建多个密钥对(如
-
密钥持久化:
- macOS/Linux:将
ssh-agent
加入开机启动 - Windows:启用 OpenSSH 服务并设置为自动启动
- macOS/Linux:将
四、常见问题解决
问题现象 | 可能原因 | 解决方案 |
---|---|---|
Permission denied | 密钥权限错误 | chmod 600 ~/.ssh/id_ed25519 |
Agent admitted failure | 代理未启动 | 重新执行 eval "$(ssh-agent -s)" |
Could not resolve hostname | 网络问题 | 检查 DNS 配置或尝试 ssh -vT git@github.com |
五、最佳实践建议
- 定期更换密钥(建议每 6 个月一次)
- 为不同平台使用不同密钥(降低风险)
- 启用密钥密码(配合密码管理器使用)
- 禁用密码认证(通过
~/.ssh/sshd_config
配置)