多Git账号配置ssh

解决多Git账号情况下push需要密码的问题

目前公司使用 git 来作为代码版本控制的工具,在家咱也会使用 github 来托管代码,多个不同 git 账号和服务器每次 push 都要输入密码特别麻烦,于是寻思怎么配置 ssh 来免除输密码的痛苦。

场景

假设咱有仨 git 账号:

移除全局的账号

1
git config --global --unset user.name && git config --global --unset user.email

创建 ssh 密钥对

1
2
3
ssh-keygen -t ecdsa -b 521 -f ~/.ssh/aaa_github  -C "aaa.github"
ssh-keygen -t ecdsa -b 521 -f ~/.ssh/bbb_github -C "bbb.github"
ssh-keygen -t ecdsa -b 521 -f ~/.ssh/ccc_gitlab -C "ccc.gitlab"

这会生成三对密钥文件在 ~/.ssh/ 目录下,把密钥们加入 ssh-agent

1
2
3
ssh-add ~/.ssh/aaa_github
ssh-add ~/.ssh/bbb_github
ssh-add ~/.ssh/ccc_gitlab

查看当前已添加的 ssh 密钥

1
ssh-add -L

修改 ssh 配置文件

这步的目的是让账户与密钥能自动匹配

打开 ~/.ssh/config 文件,没有就创建一个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
host github.com
hostname github.com
Port 22
User git
IdentityFile "~/.ssh/aaa.github"

host bbb.github
hostname github.com
Port 22
User git
IdentityFile "~/.ssh/bbb.github"

host ccc.gitlab
hostname meiliangxin.gitlab.com
Port 2222
User git
IdentityFile "~/.ssh/ccc.gitlab"

修改项目 git 配置

host 与 hostname 一致的账户不需要修改远程服务器地址,但不一致的需要修改项目的配置。比如上面的 bbb 和 ccc 账号所关联的相关项目都需要重新进行配置。

修改 remote 信息

1
2
3
4
5
6
7
8
9
10
11
12
# 去除原有 remote 信息
git remote remove origin
# 添加新的 remote 信息 这里的 host 就填 上面的 host 就行,user 填写 git 账号
git remote add origin <host>:<user>/test.git

# 如远程服务器 origin 地址为 git@github.com:bbb/test.git
git remote remove origin
git remote add origin bbb.github:ccc/test.git

# 如远程服务器 origin 地址为 git@meiliangxin.gitlab.com:ccc/test.git
git remote remove origin
git remote add origin ccc.gitlab:ccc/test.git

修改账号信息

1
2
git config --local user.name "bbb"
git config --local user.email "bbb@email.com"