Git SSH 密钥配置完整指南
1. 检查现有密钥
2. 生成新SSH密钥
3. 添加密钥到ssh-agent
4. 将公钥添加到Git托管平台
5. 测试连接
6. 配置Git使用SSH
检查现有SSH密钥
# Windows (Git Bash, PowerShell 或 CMD)
dir ~/.ssh
# 或
ls -al ~/.ssh
# macOS / Linux
ls -al ~/.ssh
如果看到以下文件,说明已有密钥:
-
id_rsa和id_rsa.pub(RSA) -
id_ed25519和id_ed25519.pub(Ed25519,推荐) -
id_ecdsa和id_ecdsa.pub(ECDSA)
生成 SSH 密钥对
打开终端或命令行工具,输入以下命令生成新的 SSH 密钥对。将 your_email@example.com 替换为你的 Git 账户邮箱:
ssh-keygen -t ed25519 -C "your_email@example.com"
若系统不支持 Ed25519 算法,可使用 RSA 算法:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
生成过程中会提示选择保存路径,默认按回车键存储在 ~/.ssh/ 目录。可设置密码加强安全性(非必填)。
添加 SSH 密钥到 SSH 代理
启动 SSH 代理服务:
eval "$(ssh-agent -s)"
将私钥添加到代理:
ssh-add ~/.ssh/id_ed25519
若使用 RSA 算法则替换为:
ssh-add ~/.ssh/id_rsa
将公钥添加到 Git 平台
复制公钥内容到剪贴板:
cat ~/.ssh/id_ed25519.pub | pbcopy # macOS
cat ~/.ssh/id_ed25519.pub | xclip # Linux
或手动打开 id_ed25519.pub 文件复制内容。
登录 Git 平台(GitHub/GitLab/Bitbucket等),进入账户设置 → SSH Keys 页面,粘贴公钥并保存。
测试 SSH 连接
验证与 Git 平台的连接状态:
ssh -T git@github.com # 测试 GitHub
ssh -T git@gitlab.com # 测试 GitLab
首次连接会提示确认主机密钥,输入 yes 即可。成功时会显示账户用户名。
配置 Git 使用 SSH
设置全局 Git 配置使用 SSH 协议:
git config --global url."git@github.com:".insteadOf "https://github.com/"
git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"
克隆仓库时使用 SSH 地址(格式:git@host:username/repo.git)。
多账户配置(可选)
若需管理多个 Git 账户,在 ~/.ssh/config 文件中添加配置:
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/work_key
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/personal_key
克隆仓库时替换主机名为配置的别名:
git clone git@github-work:company/project.git
常见问题处理
权限错误:确保密钥文件权限正确:
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
连接超时:检查防火墙或代理设置,尝试使用 -v 参数查看详细日志:
ssh -Tv git@github.com
更多推荐





所有评论(0)