从零开始:使用 SSH 克隆 GitHub 私人仓库完整指南

本文将手把手教你:如何生成 SSH 密钥、添加到 GitHub、并通过 SSH 成功克隆私有仓库。


🧱 一、什么是 SSH 密钥?为什么要用?

  • GitHub 提供两种身份验证方式:

    • HTTPS(需输入用户名和 token)
    • SSH(使用加密密钥,无需反复输入)

👉 SSH 更安全、更方便,是开发者首选。


🛠️ 二、生成 SSH 密钥对(适用于 Linux / macOS / WSL)

在终端中运行以下命令:

ssh-keygen -t ed25519 -C "你的 GitHub 邮箱"

例如:

ssh-keygen -t ed25519 -C "[email protected]"

解释参数:

参数 说明
-t ed25519 使用现代安全算法(推荐优先于 RSA)
-C 添加注释,便于 GitHub 中识别是哪台设备

📁 三、保存密钥文件

当系统提示如下时:

Enter file in which to save the key (/home/you/.ssh/id_ed25519):

直接回车即可,默认保存路径为:

  • 私钥:~/.ssh/id_ed25519(仅自己保存,切勿泄露
  • 公钥:~/.ssh/id_ed25519.pub(稍后上传到 GitHub)

🔑 四、添加公钥到 GitHub

1. 查看你的公钥内容:

cat ~/.ssh/id_ed25519.pub

输出示例:

ssh-ed25519 [email protected]

复制整行内容,不要换行、不要漏字符!


2. 添加到 GitHub:

  • 打开 GitHub
  • 点击右上角头像 → Settings
  • 进入左侧菜单:SSH and GPG keys
  • 点击绿色按钮:New SSH key
  • 填写:

    • Title:自定义(如 My Laptop
    • Key:粘贴刚刚复制的 .pub 公钥内容
  • Add SSH key

✅ 五、测试是否成功连接

在终端输入:

ssh -T [email protected]

首次会提示确认是否继续连接,输入 yes

如果输出:

Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.

🎉 恭喜!你已经成功配置 SSH。


📦 六、开始克隆你的私人仓库

现在就可以像这样通过 SSH 克隆私有仓库了:

git clone [email protected]:你的用户名/你的私有仓库.git

例如:

git clone [email protected]:xwrock-ce/dotfiles.git

🧽 七、可选步骤:避免每次输入密码

如果你在生成密钥时设置了私钥密码,但不想每次输入,可以启动 SSH agent:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

📎 附加建议

  • 不要把私钥文件上传、粘贴、分享。
  • .ssh 文件夹权限应为 700,私钥文件权限为 600

    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/id_ed25519
  • 可为不同 GitHub 账号配置多个 SSH 密钥(使用 .ssh/config

📚 总结

步骤 命令 / 操作
生成密钥 ssh-keygen -t ed25519 -C "[email protected]"
查看公钥 cat ~/.ssh/id_ed25519.pub
添加公钥 GitHub → Settings → SSH and GPG keys
测试连接 ssh -T [email protected]
克隆仓库 git clone [email protected]:user/repo.git

欢迎转载或分享本文给更多开发者!

发表回复

Your email address will not be published. Required fields are marked *.

*
*