在使用 Git 进行版本控制时,SSH 是一种安全、高效的认证方式。通过配置 SSH 密钥对(公钥和私钥),我们可以免去每次操作远程仓库时输入用户名和密码的麻烦。
本文将详细介绍如何生成 SSH 密钥对,并将其配置到 Git 和 GitHub(或其他平台)中。内容涵盖 macOS、Windows 和 Linux 三大主流操作系统平台,帮助你完成完整的 SSH 密钥配置流程。
在开始之前,先检查本地是否已经存在 SSH 密钥对:
1 |
ls -al ~/.ssh |
如果你看到如下文件,则说明已经有密钥对了:
你可以选择继续使用现有密钥,或跳过此步骤并生成新的密钥对。
无论使用哪种操作系统,我们都可以使用以下命令生成新的 SSH 密钥对:
1 |
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" |
打开 终端(Terminal)。
输入上述命令生成密钥对。
按照提示选择保存路径(默认为 ~/.ssh/id_rsa)。
设置一个可选的密码来保护你的私钥。
添加到钥匙串(推荐)
为了更方便地管理你的 SSH 私钥,在 macOS 上你可以运行以下命令将私钥添加到钥匙串中:
1 |
ssh-add --apple-use-keychain ~/.ssh/id_rsa |
这样可以避免每次使用时都要输入密码。
建议使用 Git Bash 或 PowerShell 来执行命令。
1.打开 Git Bash 或 PowerShell。
2.输入以下命令生成密钥对:
1 |
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" |
3.按照提示选择保存路径,默认为 C:\Users\<YourUsername>\.ssh\id_rsa。
4.可选:设置密码以增强安全性。
使用 SSH Agent
为了让 Windows 记住你的 SSH 密钥,你需要启动 SSH Agent 并添加你的私钥:
1 2 3 4 5 |
# 启动 SSH Agent eval $(ssh-agent -s)
# 添加私钥 ssh-add ~/.ssh/id_rsa |
如果你使用的是 Windows 10/11,也可以启用 OpenSSH 客户端:
控制面板 > 程序 > 启用或关闭 Windows 功能 > OpenSSH 客户端
1.打开 终端(Terminal)。
2.输入以下命令生成密钥对:
1 |
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" |
3.按照提示选择保存路径(默认为 ~/.ssh/id_rsa)。
4.设置一个可选的密码来保护你的私钥。
自动加载 SSH 密钥(可选)
为了不每次都手动添加密钥,可以在 ~/.bashrc 或 ~/.zshrc 中添加以下内容:
1 2 |
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_rsa |
然后重新加载配置:
1 |
source ~/.bashrc # 或 source ~/.zshrc |
1.查看公钥内容:
1 |
cat ~/.ssh/id_rsa.pub |
复制输出内容。
2.登录你的 Git 平台账户(如 GitHub、Gitee、GitLab 等)。
3.进入 Settings -> SSH and GPG keys(不同平台名称可能略有不同)。
4.点击 New SSH key,粘贴刚刚复制的内容,填写标题后点击保存。
执行以下命令测试是否能成功连接到 Git 平台(以 GitHub 为例):
1 |
ssh -T git@github.com |
如果看到类似如下信息,说明配置成功:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
如果你有多个 Git 账号(例如工作账号和个人账号),可以通过配置不同的 SSH 密钥实现多账户管理。
例如生成用于工作的密钥:
1 |
ssh-keygen -t rsa -b 4096 -C "work_email@example.com" -f ~/.ssh/id_rsa_work |
2. 创建或编辑 SSH 配置文件
1 |
nano ~/.ssh/config |
添加如下内容(以 GitHub 为例):
1 2 3 4 5 6 7 8 9 10 11 |
# 默认账号 Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa
# 工作账号 Host github-work HostName github.com User git IdentityFile ~/.ssh/id_rsa_work |
3. 测试不同账户
使用别名来测试:
1 |
ssh -T git@github-work |
提示“Permission denied (publickey)”怎么办?
如何查看当前使用的 SSH 密钥?
1 |
ssh -i ~/.ssh/id_rsa.pub -v git@github.com |
如何切换默认密钥?
修改 ~/.ssh/config 文件中的 IdentityFile 指向即可。
配置 SSH 密钥不仅提高了 Git 使用的安全性,也极大提升了开发效率。希望这篇博客能够帮助你在 macOS、Windows 和 Linux 上顺利完成 Git 的 SSH 密钥配置,愉快地进行代码协作与版本管理!