Mac设置多个GitHub账号

为多个账号设置 ssh keys

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

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

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

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

添加配置文件管理私钥

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

### Github
Host lockshell
    HostName github.com
    User lockshell
    IdentityFile ~/.ssh/id_rsa_lockshell
  
Host zhangsan
    HostName github.com
    User zhangsan
    IdentityFile ~/.ssh/id_rsa_zhangsan

更新Identities

清除缓存

$ ssh-add -D

All identities removed.

添加keys

$ ssh-add id_rsa_lockshell
Identity added: id_rsa_lockshell (lockshell@foxmail.com)

查看keys

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

测试key是否可用

$ 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 lockshell! You've successfully authenticated, but GitHub does not provide shell access.

备注

  • git clone git@github.com:lockshell/blog.git

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

本文由 络壳 原创或整理,转载请注明出处