Git 多账号配置指南:在同一台电脑管理多个 SSH Key
在日常开发中,我们经常需要同时使用多个 Git 托管平台(如 GitHub 用于开源项目,Gitee 或 GitLab 用于公司代码)。本文将教你如何通过配置 ~/.ssh/config 文件,优雅地管理多个 SSH Key。
1. 生成独立的 SSH Key
为不同的平台生成专属的 Key,关键在于不要直接回车使用默认文件名,以免覆盖旧的 Key。
生成第一个 Key (以 GitHub 为例)
BASH
ssh-keygen -t rsa -C "your_email@example.com"
关键步骤: 当提示 Enter file in which to save the key 时,输入自定义路径和文件名:
TEXT
/Users/你的用户名/.ssh/id_rsa_github
生成第二个 Key (以 Gitee 为例)
重复上述步骤,但文件名改为 id_rsa_gitee:
BASH
ssh-keygen -t rsa -C "your_email@example.com"
# 路径设置为:/Users/你的用户名/.ssh/id_rsa_gitee
2. 查看并添加公钥
生成后,你的 ~/.ssh 目录下会成对出现私钥(无后缀)和公钥(.pub)。
获取公钥内容:
BASHcat ~/.ssh/id_rsa_github.pub复制内容:将输出的字符串完整复制。
配置平台:登录 GitHub/Gitee,进入 Settings -> SSH and GPG keys -> New SSH Key,将公钥粘贴并保存。
3. 编写 SSH 配置文件 (核心)
这是实现“自动识别”的关键。我们需要创建并编辑 SSH 的本地配置文件。
创建配置文件
BASH
touch ~/.ssh/config
vim ~/.ssh/config
写入配置信息
根据你的需求修改以下模板:
SSH
# --- GitHub 配置 ---
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
# --- Gitee 配置 ---
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_gitee
# --- 公司私有 GitLab 或 IP 地址 ---
Host 192.168.1.100
HostName 192.168.1.100
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_work
参数详解
参数 | 含义 |
|---|---|
Host | 别名(建议与 HostName 一致,方便使用) |
HostName | 真实的服务器地址(域名或 IP) |
PreferredAuthentications | 优先使用的权限验证方式(通常选 publickey) |
IdentityFile | 该账号对应的私钥绝对路径 |
4. 账号验证
配置完成后,分别测试连接是否畅通。
BASH
# 测试 GitHub
ssh -T git@github.com
# 测试 Gitee
ssh -T git@gitee.com
常见交互:
首次连接: 若提示
Are you sure you want to continue connecting (yes/no)?,输入yes。成功提示: 看到
Hi username! You've successfully authenticated...即表示配置大功告成。
5. 进阶:常见问题排查
1. 权限过大错误
如果报错 Permissions 0644 for '...' are too open,说明私钥权限权限太高,执行以下命令修复:
BASH
chmod 600 ~/.ssh/config
chmod 600 ~/.ssh/id_rsa_github
2. 清除旧的 Known Hosts
如果之前连接过该域名但更换了 Key,可能会导致冲突。可以手动删除旧记录:
BASH
ssh-keygen -R github.com
3. 如何在不同项目使用不同 User?
SSH Key 解决了连接问题,但 Git 提交时的用户名和邮箱是由 git config 定义的。
全局设置:
git config --global user.name "YourName"单个项目设置:在对应项目目录下执行
git config user.name "ProjectName"(不加--global),这会覆盖全局配置,确保提交信息准确。
💡 提示:如果你是 macOS 用户,可以使用 Finder 的
Command + Shift + G快捷键,直接输入~/.ssh快速直达文件夹进行可视化管理。
