跳转至

SSH Key

HTTPS 与 SSH 的区别

从 GitLab 拉取或推送代码有两种方式:

方式 地址形式 认证方式 特点
HTTPS https://git.cx-studio.tech/group/project.git 用户名 + 密码 / Token 配置简单,每次操作可能要输入凭据
SSH git@10.223.24.16:2201/group/project.git SSH Key 一次配置,长期免密

传习社成员推荐使用 SSH。配置一次之后,git clonegit pullgit push 都不再需要输入账号密码。

生成 SSH Key

macOS / Linux 与 Windows(Git Bash、PowerShell 中的 ssh 命令)使用同一条命令:

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

your_email@example.com 换成你注册 GitLab 时使用的邮箱。

执行后会询问保存位置,直接回车使用默认路径即可;随后会要求设置 passphrase,可以留空直接回车。

生成的文件:

~/.ssh/id_ed25519       私钥
~/.ssh/id_ed25519.pub   公钥

查看公钥

cat ~/.ssh/id_ed25519.pub

输出形如:

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... your_email@example.com

复制整行内容(以 ssh-ed25519 开头,以邮箱结尾)。

添加到 GitLab

  1. 打开 https://git.cx-studio.tech
  2. 点击右上角头像 → Preferences / 偏好设置
  3. 左侧选择 SSH Keys
  4. 把公钥内容粘贴到 Key 输入框
  5. 如有需要填写标题(Title),例如 MacBook Air
  6. 点击 Add key

只上传公钥,绝不上传私钥

可以上传:

~/.ssh/id_ed25519.pub

绝对不要上传:

~/.ssh/id_ed25519

私钥文件没有任何 .pub 后缀。私钥一旦泄露,任何人都能以此身份操作你的仓库。如果你误传了私钥,请立即在 GitLab 删除该 Key,并重新生成一对新密钥。

验证配置

ssh -T git@git.cx-studio.tech

第一次连接会提示确认主机指纹,输入 yes 继续。看到类似下面的欢迎信息即表示配置成功:

Welcome to GitLab, @yourname!

校园网高速 Git

传习社 GitLab 的 Web 入口是:

https://git.cx-studio.tech

但 GitLab 实际部署在校园网内。当你在校园网中时,可以通过 SSH 内网入口进行高速 clone / pull / push:

10.223.24.16:2201

示例:

git clone ssh://git@10.223.24.16:2201/group/project.git

已有的仓库也可以切换远程地址,之后所有操作都走内网:

git remote set-url origin ssh://git@10.223.24.16:2201/group/project.git

该入口仅在校园网可用

同时使用两个远程地址也可以,例如保留 origin 为内网、https-origin 为公网:

git remote add https-origin https://git.cx-studio.tech/group/project.git

相关阅读