SSH密钥生成与最佳实践
2025-02-18
一、正确的 SSH 密钥生成方式
在生成 SSH 密钥时,应该为不同用途指定不同的文件名,避免覆盖已有密钥。以下是推荐做法:
# 生成新的 SSH 密钥,指定文件名
ssh-keygen -t rsa -b 4096 -C "你的邮箱@example.com" -f ~/.ssh/id_rsa_github
# 或者使用 Ed25519 算法(更推荐)
ssh-keygen -t ed25519 -C "你的邮箱@example.com" -f ~/.ssh/id_ed25519_github二、配置多个 SSH 密钥
修改 SSH 配置文件来管理多个密钥:
# GitHub 账号
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
# 公司 GitLab
Host gitlab.company.com
HostName gitlab.company.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab
# 其他服务器
Host prod-server
HostName prod.example.com
User deploy
IdentityFile ~/.ssh/id_rsa_prod三、密钥管理最佳实践
- 命名规范
~/.ssh/
├── id_rsa_github # GitHub 私钥
├── id_rsa_github.pub # GitHub 公钥
├── id_rsa_gitlab # GitLab 私钥
├── id_rsa_gitlab.pub # GitLab 公钥
├── id_rsa_prod # 生产服务器私钥
├── id_rsa_prod.pub # 生产服务器公钥
└── config # SSH 配置文件- 权限设置
# 设置正确的文件权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa_*
chmod 644 ~/.ssh/id_rsa_*.pub
chmod 600 ~/.ssh/config- 添加到 SSH Agent
# 启动 ssh-agent
eval "$(ssh-agent -s)"
# 添加所有私钥
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_gitlab
ssh-add ~/.ssh/id_rsa_prod四、测试配置
# 测试 GitHub 连接
ssh -T git@github.com
# 测试 GitLab 连接
ssh -T git@gitlab.company.com
# 列出已添加的密钥
ssh-add -l五、注意事项
- 生成密钥时务必指定
-f参数和文件路径 - 不同服务使用不同的密钥对
- 在
~/.ssh/config中正确配置每个 Host - 定期备份
~/.ssh目录(注意安全性) - 不要将私钥文件提交到代码仓库
这样的管理方式可以让你安全且有效地管理多个 SSH 密钥,避免密钥冲突和覆盖问题。