1. 生成 SSH 密钥
在 macOS / Linux 的终端,或者 Windows 的 PowerShell / Git Bash 中执行:
ssh-keygen -t ed25519 -C "你的GitHub邮箱"
例如:
ssh-keygen -t ed25519 -C "example@gmail.com"
接下来会看到:
Enter file in which to save the key:
直接按 Enter,默认保存到:
~/.ssh/id_ed25519
然后会让你设置密码:
Enter passphrase:
可以设置一个密码,也可以直接回车留空。
2. 启动 ssh-agent
macOS / Linux / Git Bash:
eval "$(ssh-agent -s)"
然后添加私钥:
ssh-add ~/.ssh/id_ed25519
Windows PowerShell 如果使用系统 OpenSSH,可以执行:
Get-Service ssh-agent | Set-Service -StartupType Automatic
Start-Service ssh-agent
ssh-add $env:USERPROFILE\.ssh\id_ed25519
3. 查看你的 SSH 公钥
macOS / Linux:
cat ~/.ssh/id_ed25519.pub
Windows PowerShell:
Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub
你会看到类似:
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIxxxxxxxxxxxxx example@gmail.com
复制整行。
注意:
id_ed25519是私钥,不要发给别人。id_ed25519.pub是公钥,这个可以添加到 GitHub。
4. 添加到 GitHub
进入 GitHub:
头像 → Settings → SSH and GPG keys → New SSH key
然后:
- Title:随便写,比如
MacBook、Windows PC - Key type:Authentication Key
- Key:粘贴刚才的
id_ed25519.pub
最后点击 Add SSH key。
5. 测试是否成功
执行:
ssh -T git@github.com
第一次可能出现:
Are you sure you want to continue connecting (yes/no/[fingerprint])?
输入:
yes
如果成功,一般会看到:
Hi yourusername! You've successfully authenticated, but GitHub does not provide shell access.
这就说明配置好了。
6. 使用 SSH 克隆仓库
之后不要用:
git clone https://github.com/用户名/仓库.git
而是使用 SSH 地址:
git clone git@github.com:用户名/仓库.git