通过 SSH 方式访问 GitHub 仓库

发布于:2025-04-10 ⋅ 阅读:(30) ⋅ 点赞:(0)

我们来一步一步讲解如何让 Git 通过 SSH 方式访问 GitHub 仓库,包括从零开始的详细步骤,适用于大多数系统(Linux、macOS、Windows Git Bash)。

注意最好只用 Git bash 比较好!他能够直接在 Windows 系统上面使用一些 Linux 命令,很方便!


🧭 目标

  • ✅ 本地生成 SSH 密钥
  • ✅ 添加 SSH 公钥到 GitHub
  • ✅ 配置 Git 使用 SSH URL
  • ✅ 验证是否成功连接

🛠️ 步骤一:生成 SSH 密钥

打开终端,执行:

ssh-keygen -t ed25519 -C "your_email@example.com"

🔒 如果你的系统不支持 ed25519(如旧系统),可以用 -t rsa -b 4096

系统会提示你保存路径:

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

直接按回车使用默认路径,或自定义一个文件名。

再按两次回车跳过设置密码(或者设置一段密码提高安全性)。


📋 步骤二:复制公钥并添加到 GitHub

复制公钥:

cat ~/.ssh/id_ed25519.pub

或者:

  • macOS: pbcopy < ~/.ssh/id_ed25519.pub
  • Windows Git Bash: clip < ~/.ssh/id_ed25519.pub

然后前往 GitHub:

  1. 登录 GitHub
  2. 点击右上角头像 → Settings(设置)
  3. 左边栏选择 SSH and GPG keys
  4. 点击 New SSH key
  5. Title 填写说明,比如 my-laptop
  6. Key 内容粘贴你刚复制的 id_ed25519.pub 内容
  7. 保存

⚙️ 步骤三:启动 ssh-agent 并添加私钥(首次使用需要)

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

如果你用的是自定义名称,比如 ~/.ssh/github_id_ed25519,那这里也要对应修改路径。


🧭 步骤四:配置 Git 使用 SSH URL

你可以用 HTTPS 或 SSH URL 来 clone 项目,SSH 是这样的格式:

git@github.com:username/repo.git

比如:

git clone git@github.com:octocat/Hello-World.git

如果你已经是 HTTPS 克隆的,可以切换为 SSH:

git remote set-url origin git@github.com:username/repo.git

查看当前远程地址:

git remote -v

✅ 步骤五:测试是否连接成功

执行:

ssh -T git@github.com

第一次连接时会提示:

The authenticity of host 'github.com (IP)' can't be established.
...
Are you sure you want to continue connecting (yes/no)?

输入 yes,然后你应该会看到:

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

这就说明 SSH 配置成功!


🚀 Bonus:多账户管理(可选)

如果你有多个 GitHub 账号,可以使用 ~/.ssh/config 文件做配置,例如:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519

多个账号可以配置多个别名 Host,比如 github-work.comgithub-personal.com


如果你告诉我你目前是哪个操作系统,我也可以为你生成一键脚本或图文说明!需要的话也可以帮你检查现有配置。


网站公告

今日签到

点亮在社区的每一天
去签到