使用 SSH 密钥上传 GitHub 仓库流程
本文档总结了在 Linux/macOS(或 Windows Git Bash)环境下,通过 SSH 密钥上传代码到 GitHub 仓库的完整流程,方便重复使用。
1. 检查现有 SSH 密钥
bash
ls -al ~/.ssh
- 查看是否已有密钥文件:
- 私钥:
id_rsa或id_ed25519 - 公钥:
id_rsa.pub或id_ed25519.pub
- 私钥:
- 如果已有密钥,可以直接使用;如果没有,需要生成新的。
2. 生成新的 SSH 密钥(可选)
推荐使用 Ed25519 算法:
bash
ssh-keygen -t ed25519 -C "your_email@example.com"
- 默认保存在
~/.ssh/id_ed25519 - 设置密码(可选,但建议保护私钥)
- 会生成:
- 私钥:
id_ed25519 - 公钥:
id_ed25519.pub
- 私钥:
如果已有 RSA 密钥,也可以直接使用,不影响 SSH 功能。
3. 添加私钥到 ssh-agent
启动 ssh-agent:
bash
eval "$(ssh-agent -s)"
添加私钥:
bash
ssh-add ~/.ssh/id_rsa
# 或者如果是新密钥:
# ssh-add ~/.ssh/id_ed25519
确认添加成功:
text
Identity added: /home/username/.ssh/id_rsa (your_email@example.com)
4. 将公钥添加到 GitHub
- 查看公钥内容:
bash
cat ~/.ssh/id_rsa.pub
- 登录 GitHub → Settings → SSH and GPG keys → New SSH key
- 填写 Title(如
RackServer Key),粘贴公钥内容 → 点击 Add SSH key
如果之前已有旧密钥,也可以先删除再新增。
5. 测试 SSH 连接
bash
ssh -T git@github.com
第一次会提示信任 GitHub,输入 yes。
成功输出:
text
Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.
6. 配置仓库使用 SSH
- 查看远程地址:
bash
git remote -v
- 如果显示 HTTPS 地址,需要切换为 SSH:
bash
git remote set-url origin git@github.com:username/repo.git
- 验证远程地址:
bash
git remote -v
应显示:
text
origin git@github.com:username/repo.git (fetch)
origin git@github.com:username/repo.git (push)
7. 上传代码到 GitHub
bash
# 添加修改
git add .
# 提交
git commit -m "Your commit message"
# 推送到 GitHub
git push -u origin main
- 第一次 push 使用
-u设置上游分支 - 之后可以直接
git push,无需输入用户名和密码
8. 小提示
- 以后克隆仓库也使用 SSH:
bash
git clone git@github.com:username/repo.git
- 错误的邮箱注释(
ssh-keygen -C "wrong_email")不会影响 SSH 功能,只是用于标识。
此文档可作为模板,下次在新服务器或新环境中设置 SSH 上传 GitHub 仓库时直接参考。