天生 SSH Key 并设置 GitHub/GitLab 详细教程

[复制链接]
发表于 2025-10-1 20:43:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
🔑 天生 SSH Key 并设置 GitHub/GitLab 详细教程

🟢 第 1 步:查抄是否已有 SSH Key

在 Git Bash (Windows)、终端 (Linux/macOS) 运行以下下令:
  1. ls -al ~/.ssh
复制代码
🔹 大概的输出:


  • 如果已有 SSH Key(如 id_rsa 和 id_rsa.pub)
    分析你已经天生过 SSH Key,可以跳到 第 4 步 直接添加到 GitHub/GitLab。
  • 如果 .ssh 目次不存在或没有 id_rsa 文件
    分析你必要天生新的 SSH Key,请继承下一步。

🟢 第 2 步:天生新的 SSH Key

运行以下下令:
  1. ssh-keygen -t rsa -b 4096 -C "你的邮箱"
复制代码
示例:
  1. ssh-keygen -t rsa -b 4096 -C "[email protected]"
复制代码
🔹 参数分析:


  • -t rsa :使用 RSA 算法(GitHub/GitLab 保举)
  • -b 4096 :天生 4096 位密钥(比默认 2048 位更安全)
  • -C "你的邮箱" :添加解释(通常是你的 GitHub/GitLab 绑定邮箱)
💡 体系会扣问以下题目:

  • Enter file in which to save the key (~/.ssh/id_rsa 默认回车)
    1. Enter file in which to save the key (/home/your-user/.ssh/id_rsa):
    复制代码

    • 直接回车 使用默认路径(保举)
    • 如果已有密钥,可以换个名字,如 id_rsa_github

  • Enter passphrase(输入暗码,可留空)
    1. Enter passphrase (empty for no passphrase):
    复制代码

    • 发起直接回车(否则每次使用 SSH 都要输入暗码)

天生乐成后,会在 ~/.ssh/ 目次下创建两个文件:
  1. ~/.ssh/id_rsa      # 私钥(不要分享)
  2. ~/.ssh/id_rsa.pub  # 公钥(需要添加到 GitHub/GitLab)
复制代码

🟢 第 3 步:启动 SSH Agent 并添加密钥

1️⃣ 启动 SSH 署理(用于管理密钥):
  1. eval "$(ssh-agent -s)"
复制代码
乐成时会返回:
  1. Agent pid 12345
复制代码
2️⃣ 将私钥添加到 SSH 署理:
  1. ssh-add ~/.ssh/id_rsa
复制代码
如果你的私钥文件名不是 id_rsa,请修改为现实名称:
  1. ssh-add ~/.ssh/id_rsa
  2. _github
复制代码
💡 如果报错:
  1. Could not open a connection to your authentication agent
复制代码
请先运行:
  1. eval $(ssh-agent)
  2. ssh-add ~/.ssh/id_rsa
复制代码

🟢 第 4 步:复制 SSH 公钥

运行:
  1. cat ~/.ssh/id_rsa.pub
复制代码
🔹 复制公钥的方法:


  • Windows Git Bash:
    1. clip < ~/.ssh/id_rsa.pub
    复制代码
  • macOS:
    1. pbcopy < ~/.ssh/id_rsa.pub
    复制代码
  • Linux(手动复制):
    1. cat ~/.ssh/id_rsa.pub
    复制代码

🟢 第 5 步:添加 SSH Key 到 GitHub/GitLab

🔹 GitHub:

  • 打开 GitHub SSH 设置
  • 点击 New SSH Key
  • Title:任意填(如 “My Laptop”)
  • Key:粘贴 id_rsa.pub 里的内容
  • 点击 Add SSH Key
🔹 GitLab:

  • 打开 Preferences -> SSH Keys
  • 粘贴 id_rsa.pub 的内容
  • 点击 Add Key

🟢 第 6 步:测试 SSH 毗连

复制代码
如果乐成,会看到:
  1. Hi <your-username>! You've successfully authenticated, but GitHub does not provide shell access.
复制代码
🎉 SSH Key 设置乐成!

🟢 第 7 步:设置 Git 使用 SSH 方式拉取代码

默认情况下,Git 大概还在使用 HTTPS,必要手动改为 SSH。
✅ 设置全局 Git 远程 URL 方式:
  1. git config --global url."[email protected]:".insteadOf "https://github.com/"
复制代码
如许你 git clone 或 git push 就不会要求输入 GitHub 账号和暗码了!

🟢 第 8 步:使用 SSH 克隆 GitHub/GitLab 堆栈

💡 HTTPS 方式(必要输入暗码):
  1. git clone https://github.com/your-username/repository.git
复制代码
💡 SSH 方式(不必要输入暗码):
  1. git clone [email protected]:your-username/repository.git
复制代码
如果使用 GitLab:
  1. git clone [email protected]:your-username/repository.git
复制代码

🎯 总结

✔ 查抄 SSH Key
✔ 天生 SSH Key
✔ 启动 SSH 署理 & 添加密钥
✔ 复制公钥 & 添加到 GitHub/GitLab
✔ 测试 SSH 毗连
✔ 使用 SSH 克隆堆栈
💡 完成后,你的 Git 毗连将更加安全,且无需每次输入暗码!🚀
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表