1. 检查现有 SSH 密钥
首先检查是否已经有 SSH 密钥:
ls -la ~/.ssh
如果存在以下文件,说明已经有 SSH 密钥:
id_rsa
(私钥)id_rsa.pub
(公钥)
2. 生成新的 SSH 密钥
如果没有密钥或需要新的密钥,执行:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
或者使用更安全的 Ed25519 算法:
ssh-keygen -t ed25519 -C "your_email@example.com"
3. 启动 SSH-Agent
# 启动 ssh-agent
eval "$(ssh-agent -s)"
# 或者添加到 ~/.zshrc 或 ~/.bash_profile 中自动启动
echo 'eval "$(ssh-agent -s)"' >> ~/.zshrc
4. 添加私钥到 SSH-Agent
# 添加默认私钥
ssh-add ~/.ssh/id_rsa
# 或者添加 Ed25519 私钥
ssh-add ~/.ssh/id_ed25519
5. 复制公钥
# 复制 RSA 公钥到剪贴板
pbcopy < ~/.ssh/id_rsa.pub
# 或者复制 Ed25519 公钥
pbcopy < ~/.ssh/id_ed25519.pub
6. 配置 Git 用户信息
git config --global user.name "你的用户名"
git config --global user.email "your_email@example.com"
7. 测试 SSH 连接
对于 GitHub:
ssh -T git@github.com
对于 GitLab:
ssh -T git@gitlab.com
8. 配置多个 SSH 密钥
如果需要为不同服务配置不同的密钥,创建 ~/.ssh/config
文件:
# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
# GitLab
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab
# 公司 Git 服务器
Host company-git
HostName git.company.com
User git
IdentityFile ~/.ssh/id_rsa_company
9. 常用命令
# 查看所有 SSH 密钥
ssh-add -l
# 删除特定密钥
ssh-add -d ~/.ssh/id_rsa
# 删除所有密钥
ssh-add -D
# 测试特定主机的连接
ssh -T git@github.com
10. 故障排除
权限问题:
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
SSH-Agent 问题:
# 重启 ssh-agent
killall ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
连接超时:
# 测试连接并显示详细信息
ssh -vT git@github.com
11. 安全建议
- 定期更换密钥:建议每年更换一次 SSH 密钥
- 使用强密码:生成密钥时设置强密码
- 限制密钥权限:确保私钥文件权限为 600
- 备份密钥:安全备份私钥文件
12. 验证配置
完成配置后,可以克隆一个私有仓库来验证:
git clone git@github.com:username/repository.git
这样你就完成了 Mac 上 Git 私钥的完整配置!如果遇到任何问题,可以告诉我具体的错误信息。