同一台电脑上要连GitHub、公司GitLab,还要连其他Git仓库,账户来回切,推代码总报错,另一件烦事:明明在公司仓库提交,结果commit记录里显示的是个人邮箱,被同事和领导围观。

如果你也遇到这些问题,别急着删.ssh文件夹重来,这篇文章能帮你一次性搞定。

SSH密钥多账户管理

最靠谱的方式,没有之一。

生成不同用途的密钥对

别偷懒用同一个密钥,给每个平台单独生成:

1
2
3
4
5
# GitHub专用
ssh-keygen -t ed25519 -C "your_email@github.com" -f ~/.ssh/id_ed25519_github

# 公司GitLab专用
ssh-keygen -t ed25519 -C "your_email@company.com" -f ~/.ssh/id_ed25519_gitlab

把公钥加到对应的平台

这个不用多说,打开GitHub/GitLab的设置页面,找到SSH Keys,把.pub文件的内容完整复制进去。

注意:一定要复制.pub结尾的文件,而不是私钥文件。

配置SSH客户端

编辑~/.ssh/config文件(没有就新建一个):

1
2
3
4
5
6
7
8
9
10
11
12
13
# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes

# 公司GitLab
Host gitlab.company.com
HostName gitlab.company.com
User git
IdentityFile ~/.ssh/id_ed25519_gitlab
IdentitiesOnly yes

测试连接

1
2
ssh -T git@github.com
ssh -T git@gitlab.company.com

根据域名自动切换身份

解决了认证问题,还有个麻烦事:不同仓库要用不同的用户名和邮箱。

以前的做法是每个仓库单独配置:

1
2
git config user.name "张三"
git config user.email "zhangsan@company.com"

项目一多就记不住了,老忘。Git 2.36之后有了更好的方式——根据远程仓库域名或者目录自动切换。

创建身份配置文件

~/.gitconfig-work(公司用):

1
2
3
[user]
name = 张三
email = zhangsan@company.com

~/.gitconfig-personal(个人用):

1
2
3
[user]
name = San Zhang
email = san.zhang@gmail.com

配置自动规则

编辑~/.gitconfig主配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
# 兜底身份(可选)
[user]
name = 默认用户
email = default@email.com

# 公司GitLab走公司配置
[includeIf "hasconfig:remote.*.url:git@gitlab.company.com:*/**"]
path = ~/.gitconfig-work

# GitHub走个人配置
[includeIf "hasconfig:remote.*.url:git@github.com:*/**"]
path = ~/.gitconfig-personal

验证

进入任意一个仓库目录,运行:

1
2
git config user.name
git config user.email

如果输出的是你期望的身份,说明一切正常。以后新克隆的仓库都不用再手动设置了。