Skip to main content

5. Git SSH

使用 SSH 协议进行 Git 仓库操作能够提升安全性与自动化程度,特别适用于私有仓库与持续集成环境。本指南将介绍 SSH 的基本原理、生成密钥步骤,以及如何将其与 Git 配合使用。


🔐 SSH 配置的基本原理

SSH(Secure Shell)是一种加密的网络协议,用于安全地进行远程登录与数据传输。

在 Git 中使用 SSH,主要流程为:

  1. 本地生成一对 SSH 密钥(公钥 + 私钥)
  2. 将公钥添加到代码托管平台(如 GitHub、GitLab)
  3. 本地通过私钥与远程平台进行认证
  4. 实现免密拉取 / 推送代码

🧰 步骤一:检查本地是否已有 SSH 密钥

ls -al ~/.ssh

如果你看到 id_rsa(私钥)和 id_rsa.pub(公钥)文件,说明已有密钥。


✨ 步骤二:生成新的 SSH 密钥对

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
tip

推荐使用 ed25519 类型(更安全更快):

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

默认路径为 ~/.ssh/id_ed25519,也可以自定义路径。


📋 步骤三:添加 SSH Key 到代理(ssh-agent)

# 启动 ssh-agent
eval "$(ssh-agent -s)"

# 添加私钥
ssh-add ~/.ssh/id_ed25519
Windows 用户注意事项

请使用 Git Bash 或 WSL 执行上述命令,确保 ssh-agent 服务已开启。


☁️ 步骤四:将公钥添加到代码托管平台

复制公钥内容:

cat ~/.ssh/id_ed25519.pub

粘贴到 GitHub / GitLab / Gitee 等平台的 SSH Key 配置界面中。


🔗 步骤五:配置 SSH 主机别名(可选)

# 编辑 SSH 配置文件
vim ~/.ssh/config

添加如下内容:

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

这样就可以避免多个仓库冲突或多个 Git 账号共用。


🔍 步骤六:测试 SSH 连接是否成功

ssh -T git@github.com

成功输出示例:

Hi your-username! You've successfully authenticated...
caution

首次连接时会提示是否继续连接,输入 yes 并回车即可。


📦 步骤七:使用 SSH 地址克隆仓库

git clone git@github.com:your-username/your-repo.git

SSH 地址格式通常为:

git@host:username/repo.git

💡 多账号管理技巧

配置多个 Git 账号(如 GitHub 与 GitLab)
# ~/.ssh/config
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github

Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab

使用对应的 SSH 地址:

git@github.com:xxx.git
git@gitlab.com:yyy.git

✅ 总结

  • 使用 SSH 能够实现 Git 的免密访问和安全连接;
  • SSH Key 包括私钥(本地保密)和公钥(上传远程);
  • 通过 ssh-agent 和 config 文件管理多账号;
  • 建议使用 ed25519 类型密钥并开启 ssh-agent。

📚 推荐链接