为多个账号设置 ssh keys

假定我们有两个账号,一个lisi,一个zhangsan。
分别用不同 github 账号对应的邮箱生成 ssh key,示例:

1
2
3
4
5
6
7
8
9
$ ssh-keygen -t rsa -C "lisi@yyy.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/lisi/.ssh/id_rsa): id_rsa_lisi
...

$ ssh-keygen -t rsa -C "zhangsan@xxx.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/lisi/.ssh/id_rsa): id_rsa_zhangsan
...

将公钥添加到对应的 github 账号

添加配置文件管理私钥

.ssh目录下新建config文件,添加如下配置:

1
2
3
4
5
6
7
8
9
10
### Github
Host lisi
HostName github.com
User lisi
IdentityFile ~/.ssh/id_rsa_lisi

Host zhangsan
HostName github.com
User zhangsan
IdentityFile ~/.ssh/id_rsa_zhangsan

更新Identities

清除缓存

1
2
3
$ ssh-add -D

All identities removed.

添加keys

1
2
$ ssh-add id_rsa_lisi
Identity added: id_rsa_lisi (lisi@yyy.com)

查看keys

1
2
3
$ ssh-add -l
2048 SHA256:w0XXyh0hy/2yHSazwYerQ+8yKQ9LVxKWtEs3sl8RFq0 zhangsan@xxx.com (RSA)
2048 SHA256:QgaUvrNlbuwm9B2yRLzc5/eug4VjQxoToh3E6U+xq58 lisi@yyy.com (RSA)

测试key是否可用

1
2
3
$ ssh -T git@github.com
Warning: Permanently added the RSA host key for IP address '13.250.177.223' to the list of known hosts.
Hi lisi! You've successfully authenticated, but GitHub does not provide shell access.

备注

  • git clone git@github.com:lisi/blog.git
  • 如果公司账号和GitHub账号使用不同的域名,当clone一个新 Repos 时,如果其 ssh 地址为 git@github.com:username/xxx.git,使用 git@company:username/xxx.git 即可