0%

macOS 下 Git 多账号配置,同时管理多个 SSH Key

很多人有这样的需求:不仅有 GitHub,还会在 BitBucket 上管理私有的代码库,同时可能因为访问国外服务器速度慢,还会在码云、Coding 上有自己的代码库。HTTPS 毕竟不如 SSH 来的方便和安全,于是我们就有了使用多对 SSH 密钥的需求。

生成密钥

先查看家目录是否有一个 .ssh 的目录,如果没有说明还没有任何 SSH 密钥,我们先输入如下命令生成密钥。

1
2
3
$ ssh-keygen -t rsa -C "qiweipeng@hotmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/qiweipeng/.ssh/id_rsa):

这里让我们输入密钥保存的位置,如果直接回车,默认的保存位置就是家目录中的 .ssh 目录,默认名字是 id_rsa,由于我们需要为不同的网站设置不同的,所以我们自定义文件名 id_rsa_github,之后的密码可以不设置,我们两次回车:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Enter file in which to save the key (/Users/qiweipeng/.ssh/id_rsa):/Users/qiweipeng/.ssh/id_rsa_github
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_github.
Your public key has been saved in id_rsa_github.pub.
The key fingerprint is:
SHA256:SRqk4YpV6A2tWc1JZDLn5jJVycjYSpffl+0Y55v+meM qiweipeng@hotmail.com
The key's randomart image is:
+---[RSA 2048]----+
| o=O*=.. |
| oo=XX.o |
| ..Boo=... o |
| o+.o+ +... + o |
|. . o o S . * |
| o . o |
| o |
| o.o|
| .oEo|
+----[SHA256]-----+

此时一对 SHH 密钥已经生成好了,他们分别是 id_rsa_githubid_rsa_github.pub,对应着私钥和公钥,位置就在我们指定的 .ssh 目录下。

之后,我们以同样方法再创建一对密钥,命名为 id_rsa_bitbucketid_rsa_bitbucket.pub,这样,我们第一步生成密钥的工作就做完了。

上传公钥

以 GitHub 为例,首先查看公钥然后复制:

1
$ cat ~/.ssh/id_rsa_github.pub

登陆 GitHub,在 Settings - SSH and CPG keys 的位置点击 New SSH key,然后粘贴公钥。

完成配置

此时我们仅仅创建了两对密钥,因此 .ssh 文件夹中也只有这两对密钥;我们在这个文件夹创建一个 config 文件:

1
$ touch config

之后打开填入如下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
User qiweipeng

# bitbucket
Host bitbucket.org
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_bitbucket
User qiweipeng

这里面重要的一个是 HostName,一定要填写正确,一个是 IdentityFile 就填写对应的私钥。

如果是码云,HostName 就是 gitee.com;如果是 Coding 呢 HostName 就是 git.coding.net

测试

同样以 GitHub 为例

1
2
3
4
5
6
$ ssh -T git@github.com
The authenticity of host 'github.com (13.229.188.59)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,13.229.188.59' (RSA) to the list of known hosts.
Hi qiweipeng! You've successfully authenticated, but GitHub does not provide shell access.

第一次链接需要确认一下,它给了一个 RSA key fingerprint,这是为了安全考虑,让你确认一下这个指纹是否是来自 GitHub 服务器的,我们可以对照这里查看,如果没问题就 yes,之后可以看到已经成功连接啦!

此时我们查看 .ssh 目录,可以看到,多了一个 known_hosts 文件,这是一个信任列表,又上面的命令也能看到 Permanently added 'github.com,13.229.188.59' (RSA) to the list of known hosts.

类似地,BitBucket、码云、Coding 的命令分别是 git@bitbucket.orggit@gitee.comgit@git.coding.net,不出意外,是可以测试成功的。

到此为止,我们就可以使用 Git 进行多账号操作了。