今天要在一台新PC上配置对GitHub的SSH访问, 此过程可能会中未来不定时地再来一次。
以往的做法是, 自己搜索执行步骤, 执行。 记录到知识库, 同时发一个博客(可选)。
在一台新 PC 上配置 Git 的 SSH 访问,主要流程是“生成密钥 -> 关联平台 -> 验证连接”。以下是针对 Windows/macOS/Linux 通用的详细步骤:
第一步:检查现有的 SSH 密钥
在生成新密钥前,先确认电脑是否已经有过密钥。
-
打开终端(Windows 推荐使用 Git Bash,macOS/Linux 使用 Terminal)。
-
输入以下命令:
Bashls -al ~/.ssh -
结果判断:如果看到
id_rsa和id_rsa.pub(或id_ed25519),说明已有密钥。如果没有该文件夹或文件,请继续下一步。
第二步:生成新的 SSH 密钥
建议使用更安全、更高效的 Ed25519 算法(如果你的服务器较老,请使用 RSA)。
-
在终端输入(将邮箱替换为你 Git 平台的注册邮箱):
Bashssh-keygen -t ed25519 -C "your_email@example.com"-
注:如果提示不支持 ed25519,请改用:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-
-
三连回车:
-
提示
Enter file in which to save the key:直接回车(使用默认路径)。 -
提示
Enter passphrase:直接回车(不设密码,方便日后自动推送)。 -
再次确认密码:直接回车。
-
第三步:将 SSH 密钥添加到本地 Agent
这一步确保你的私钥被系统正确管理。
-
启动 ssh-agent:
Basheval "$(ssh-agent -s)" -
将私钥添加到 agent:
Bashssh-add ~/.ssh/id_ed25519
第四步:将公钥添加到 Git 平台 (GitHub/GitLab/Gitee)
你需要把“锁”留在电脑上,把“钥匙”交给服务器。
-
复制公钥内容:
-
Windows (Git Bash):
cat ~/.ssh/id_ed25519.pub | clip -
macOS:
pbcopy < ~/.ssh/id_ed25519.pub -
Linux:
cat ~/.ssh/id_ed25519.pub(手动复制打印出的内容)
-
-
登录你的 Git 平台:
-
找到 Settings -> SSH and GPG keys -> New SSH Key。
-
Title:起个名字(如:
Work_Laptop_2026)。 -
Key:粘贴刚才复制的内容。
-
点击 Add SSH Key。
-
第五步:验证连接
这是最关键的一步。
-
在终端输入(以 GitHub 为例):
Bashssh -T git@github.com -
注意:第一次连接会提示
The authenticity of host... can't be established.,这是正常的,请输入yes并回车。 -
成功标志:如果看到
Hi [你的用户名]! You've successfully authenticated...,说明配置成功!
第六步:最后一步——配置 Git 用户名和邮箱
即使配置了 SSH,本地提交记录仍需要身份标识:
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
💡 进阶:如果你有多个 Git 账号(公司 + 私人)
如果你需要在一台电脑上同时访问 GitHub 和公司私有 GitLab,你需要在 ~/.ssh/ 目录下创建一个名为 config 的文件,内容如下:
# GitHub 个人账号
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
# 公司 GitLab 账号
Host gitlab.company.com
HostName gitlab.company.com
User git
IdentityFile ~/.ssh/id_ed25519_work
配置完成后,你打算先克隆哪一个仓库进行测试?
我在最后追问了下, 步骤3是否可省略, 答:大部分情况是。 balabala...
AI很话唠。
浙公网安备 33010602011771号