在 Ubuntu 中使用 SSH 克隆 Git 仓库的步骤如下:
1. 生成 SSH 密钥(如果还没有)
bash
ssh-keygen -t ed25519 -C "[email protected]"
(按 Enter 接受默认保存位置,设置密码短语可选)
2. 将 SSH 密钥添加到 ssh-agent
bash
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
3. 将公钥添加到 Git 服务商
-
查看公钥:
bashcat ~/.ssh/id_ed25519.pub
-
复制输出内容
-
添加到你的 Git 平台(GitHub/GitLab等)的 SSH 设置中
(1)点进GitHub的设置settings→选择「SSH和GPG keys」选项→「New SSH key」

(2)填写刚刚的公钥(cat ~/.ssh/id_ed25519.pub命令的输出结果)

(3)确认添加,完成。
4. 测试 SSH 连接
bash
ssh -T [email protected] # 如果是 GitHub
输出包含"successful"之类的祝贺你成功的语句。
5. 克隆仓库
使用仓库的 SSH URL(格式通常是 [email protected]:user/repo.git
):
bash
git clone [email protected]:user/repository.git
常见问题解决
-
权限错误 :确保
~/.ssh
目录权限是 700,密钥文件是 600bashchmod 700 ~/.ssh chmod 600 ~/.ssh/id_ed25519*
-
不同平台 :GitLab/Bitbucket 等需要对应域名(如
[email protected]
)
这样就完成了通过 SSH 安全克隆 Git 仓库的操作。