3.2 KiB
3.2 KiB
配置ssh密钥快速指南
配置密钥可以实现快速登录就是了
快速指南:生成 SSH 密钥对用于 Git
1. 检查现有 SSH 密钥
Linux / macOS
ls -al ~/.ssh
Windows(PowerShell / Git Bash)
# PowerShell
Get-ChildItem -Path $env:USERPROFILE\.ssh
# Git Bash
ls -al /c/Users/YourUserName/.ssh
常见文件:
id_rsa/id_rsa.pub(RSA 密钥对)id_ed25519/id_ed25519.pub(ED25519 密钥对)
⚠️ 注意:如果已有密钥且希望复用,可跳过生成步骤。
2. 生成新的 SSH 密钥对
2.1 使用 ED25519(推荐,安全且快速)
Linux / macOS
ssh-keygen -t ed25519 -C "your_email@example.com"
Windows(PowerShell / Git Bash)
# Git Bash / PowerShell
ssh-keygen -t ed25519 -C "your_email@example.com"
-C用于添加备注(通常填写邮箱)- 系统会提示:
- 文件名(默认
~/.ssh/id_ed25519或C:\Users\YourUserName\.ssh\id_ed25519) - 密码短语(可选,用于额外保护私钥)
- 文件名(默认
2.2 使用 RSA(兼容性更好,但略旧)
Linux / macOS
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Windows(PowerShell / Git Bash)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-b 4096指定密钥长度,推荐 4096 位
3. 添加 SSH 私钥到 SSH Agent
Linux / macOS
- 启动 ssh-agent:
eval "$(ssh-agent -s)"
- 添加私钥:
ssh-add ~/.ssh/id_ed25519
# 或者 RSA 私钥
ssh-add ~/.ssh/id_rsa
Windows(PowerShell / Git Bash)
- 启动 ssh-agent 服务:
# PowerShell
Start-Service ssh-agent
# 设置为开机自启(可选)
Set-Service -Name ssh-agent -StartupType Automatic
- 添加私钥:
ssh-add C:\Users\YourUserName\.ssh\id_ed25519
# 或者 RSA 私钥
ssh-add C:\Users\YourUserName\.ssh\id_rsa
🔑 如果你设置了密码短语,需要在此步骤输入一次。
4. 将公钥添加到 Git 账号
Linux / macOS
cat ~/.ssh/id_ed25519.pub
Windows(PowerShell / Git Bash)
# PowerShell
Get-Content C:\Users\YourUserName\.ssh\id_ed25519.pub
# Git Bash
cat /c/Users/YourUserName/.ssh/id_ed25519.pub
然后登录 Git 平台(GitHub、GitLab、Gitee 等)添加公钥。
5. 测试连接
Linux / macOS / Windows
ssh -T git@github.com
- 第一次连接可能提示是否继续,输入
yes - 成功提示示例:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
6. 配置 Git 使用 SSH
Linux / macOS / Windows
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
git remote set-url origin git@github.com:username/repo.git
- 确保远程仓库使用 SSH 地址 而不是 HTTPS
✅ 小贴士
- ED25519 优先:更安全、更短更快
- 私钥妥善保管:不要上传到任何平台
- 不同机器不同密钥:每台设备建议生成独立密钥
- 密码短语保护:防止密钥泄露被直接使用