Ubuntu:Git SSH密钥配置的完整流程
🛠 Ubuntu 下 Git SSH 密钥配置完整流程
1️⃣ 检查是否已有 SSH 密钥
先看看本地有没有旧的 SSH 密钥:
ls -al ~/.ssh
可能会看到这些文件:
id_rsa
/id_rsa.pub
→ 旧的 RSA 密钥对id_ed25519
/id_ed25519.pub
→ 较新的 ED25519 密钥对
如果已经存在,而且没过期,可以直接用。如果显示密钥过期,建议重新生成。
2️⃣ 生成新的 SSH 密钥对
推荐使用更安全、更快的 ED25519 算法
ssh-keygen -t ed25519 -C "你的邮箱"
执行后会提示:
Enter file in which to save the key (/home/youruser/.ssh/id_ed25519):
直接回车(保存在默认路径),如果要保留旧密钥,可以改个名字,比如 id_ed25519_new
。
然后会提示输入密码短语,可以直接回车跳过(不设置密码)。
生成完成后,你会得到两个文件:
~/.ssh/id_ed25519
→ 私钥,自己保留,不要泄露~/.ssh/id_ed25519.pub
→ 公钥,用来上传到远程仓库
3️⃣ 将公钥添加到远程 Git 仓库
如果用 GitHub
cat ~/.ssh/id_ed25519.pub
复制输出内容,然后:
登录 GitHub
进入 Settings → SSH and GPG keys
点击 New SSH key
填名字(随便取),把复制的公钥粘贴进去,保存
如果用 GitLab
登录 GitLab
进入 Profile → Preferences → SSH Keys
粘贴公钥,保存
4️⃣ 测试 SSH 连接
GitHub:
ssh -T git@github.com
GitLab:
ssh -T git@gitlab.com
如果成功,会输出类似:
Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.
5️⃣ 配置 Git 使用 SSH 协议
如果你之前用 HTTPS clone 的仓库,建议改成 SSH 远程地址:
git remote set-url origin git@github.com:your-username/your-repo.git
查看确认:
git remote -v
应该显示 SSH 地址。
6️⃣ 添加到 ssh-agent(可选)
为了避免每次都要输入密码,可以把密钥加入 ssh-agent:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
7️⃣ 拉取代码测试
git pull origin 分支名
到此为止,你的 Ubuntu 已经配置好了新的 SSH key,可以正常拉取和推送代码。