一、检查是否已有 SSH 密钥
ls -al ~/.ssh
如果看到 id_ed25519 / id_ed25519.pub 或 id_rsa / id_rsa.pub,说明已有密钥,可直接跳到 第三步。
二、生成新的 SSH 密钥(推荐 ed25519),执行后三次回车即可(使用默认路径 ~/.ssh/id_ed25519,不设 passphrase 最省事):
ssh-keygen -t ed25519 -C "你的邮箱@example.com"
Enter file in which to save the key (/Users/你/.ssh/id_ed25519): ⏎
Enter passphrase (empty for no passphrase): ⏎
Enter same passphrase again: ⏎
生成后会得到两个文件:
~/.ssh/id_ed25519 ← 私钥,绝对不能泄露
~/.ssh/id_ed25519.pub ← 公钥,用于上传到 Git 服务器
三、将私钥加入 ssh-agent(Mac 特有步骤)
- 启动 ssh-agent
eval "$(ssh-agent -s)"
- 配置 ~/.ssh/config(让 Mac 钥匙串记住密钥)
touch ~/.ssh/config
open -e ~/.ssh/config
在文件中写入(根据你的 Git 服务器选对应的 Host,多个平台可一起写):
注意有端口号的需要加上 Port 端口号
Host github.com
HostName github.com
User git
Port 端口号 //有就写
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519
- 把私钥加到 ssh-agent 和钥匙串
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
四、复制公钥到剪贴板
bcopy < ~/.ssh/id_ed25519.pub
五、把公钥添加到 Git 服务器
GitHub
登录 GitHub → 右上角头像 → Settings
左侧 SSH and GPG keys → New SSH key
Title 填个名字(如 MacBook Pro),Key 粘贴刚复制的公钥 → Add SSH key
GitLab(含公司自建)
登录 → 右上角头像 → Preferences → SSH Keys
Key 粘贴公钥,Title 起个名 → Add key
Gitee / 码云
登录 → 头像 → 设置 → SSH 公钥
粘贴公钥,标题任意 → 确定
六、测试连接
ssh -T git@gitlab.your-company.com
# 1. 生成密钥
ssh-keygen -t ed25519 -C "your@email.com" # 三回车
# 2. 启动 agent 并加入钥匙串
eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
# 3. 复制公钥
pbcopy < ~/.ssh/id_ed25519.pub
# 4. 粘贴到 GitHub/GitLab 的 SSH Keys 页面
# 5. 测试
ssh -T git@github.com
# 6. 克隆
git clone git@github.com:owner/repo.git