一、准备工作
生成多对 SSH Key
为每个用户(如“个人”、“公司”)生成一对独立的 SSH Key。
示例(在 Git Bash 或 Linux 终端中执行):
# 个人 ssh-keygen -t rsa -b 4096 -C "personal@example.com" -f ~/.ssh/id_rsa_personal # 公司 ssh-keygen -t rsa -b 4096 -C "work@example.com" -f ~/.ssh/id_rsa_work
将公钥添加到对应的 Git 服务器
- 登录 GitHub/Gitee 等,将
~/.ssh/id_rsa_personal.pub
与~/.ssh/id_rsa_work.pub
分别添加到对应账号的 SSH Keys 中。
- 登录 GitHub/Gitee 等,将
二、统一 SSH 配置
编辑(或创建)SSH 配置文件,指明不同 Host 使用不同密钥。
注意:Linux 下私钥文件权限必须为
600
,目录~/.ssh
必须为700
,否则 SSH 将拒绝加载密钥。chmod 600 ~/.ssh/id_rsa_personal ~/.ssh/id_rsa_work chmod 700 ~/.ssh
在 ~/.ssh/config
(Windows 下为 C:\Users\<用户名>\.ssh\config
)中添加:
# 个人账号
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_personal
IdentitiesOnly yes
# 公司账号
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work
IdentitiesOnly yes
Host
为自定义主机别名,用于替代github.com
。IdentityFile
指向对应私钥的绝对路径。IdentitiesOnly yes
强制仅使用上述 Key。
三、Git 层面自动切换配置
3.1 全局 Git 配置打基础
在任意环境下,都建议先在全局(~/.gitconfig
或 Windows %USERPROFILE%\.gitconfig
)设置“默认”身份,例如公司:
[user]
name = 公司用户名
email = work@example.com
3.2 基于路径的自动切换(Linux/Windows 均可)
Git 2.13+ 支持 includeIf
,可按目录自动加载不同配置[1]。
创建个人配置文件
# ~/.gitconfig-personal [user] name = 个人用户名 email = personal@example.com
修改主配置
在~/.gitconfig
(或 Windows 上的%USERPROFILE%\.gitconfig
)末尾添加:[includeIf "gitdir:~/Code/personal/"] path = ~/.gitconfig-personal
gitdir:
后面须为对应目录的绝对路径,末尾加/
。Windows 下也支持:
[includeIf "gitdir:C:/Users/用户名/Code/personal/"] path = C:/Users/用户名/.gitconfig-personal
保存后,进入该目录内执行:
git config user.name # 应输出“个人用户名” git config user.email # 应输出“personal@example.com”
四、克隆/设置远程仓库时使用 Host 别名
无论 Windows 还是 Linux,克隆或修改远程 URL 时,将 github.com
替换为 github-personal
或 github-work
,与 ~/.ssh/config
中的保持一致:
# 个人项目
git clone git@github-personal:username/repo.git
# 公司项目
git clone git@github-work: company/repo.git
如果项目已存在,可运行:
git remote set-url origin git@github-personal:username/repo.git
五、Windows 端额外说明
在 Git Bash 中按上述方法即可。
如果使用 PuTTY/Pageant:
- 将 OpenSSH 格式的私钥转换为 PPK:
puttygen id_rsa_personal -o id_rsa_personal.ppk
。 - 在 Pageant 中加载对应 PPK 文件。
- 修改项目的远程地址同样使用
github-personal
等别名。
- 将 OpenSSH 格式的私钥转换为 PPK:
六、常见问题与注意事项
私钥权限过宽导致加载失败
错误示例(Ubuntu):
Permissions 0664 for '/home/user/.ssh/id_rsa' are too open. This private key will be ignored.
需执行
chmod 600 ~/.ssh/id_rsa_*
[2]。
配置文件路径中不要加双引号
- 如
IdentityFile "~/.ssh/id_rsa"
可能无法被解析,宜写作IdentityFile ~/.ssh/id_rsa
。
- 如
includeIf
版本兼容- Git ≥2.19 才支持在路径中使用
~
。若出现问题请使用绝对路径。
- Git ≥2.19 才支持在路径中使用
验证方式
ssh -T git@github-personal # 应返回“Hi <user>! You’ve successfully authenticated…” ssh -T git@github-work