Git默认是一台设备一个SSH-Key,但是实际情况中,我们会将个人和公司的Git账号分开,公司的邮箱注册公司内部的代码管理平台,平时工作用;个人的邮箱注册GitHub、Gitee等,自己开发用,那么如何用Git去生成、配置多个账户呢?
1. 生成SSH-Key
首先,我们先生成一个公司用的SSH-Key:
$ ssh-keygen -t rsa -C 'xxxxx@company.com' -f ~/.ssh/company_id_rsa
中间的步骤可以按照提示回车,生成好后如下图所示:
# 输入
ssh-keygen -t rsa -C 'xxxxx@company.com' -f ./company_id_rsa
# 输出
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in ./company_id_rsa.
Your public key has been saved in ./company_id_rsa.pub.
The key fingerprint is:
SHA256:b+2jkEj84C3sEXtAhPth1hQoofQP4TYR1zuqjOhro1M xxxxx@company.com
The key's randomart image is:
+---[RSA 3072]----+
| . =+oo.. |
| . +o=. o |
| . *o.o . |
| ..*+ + |
| +BoS. |
| E +oO o . |
| o o .B * o . |
|oo. o. + o .. |
|=+o . .... |
+----[SHA256]-----+
再生成一个个人用的SSH-Key:
$ ssh-keygen -t rsa -C 'xxxxx@126.com' -f ~/.ssh/github_id_rsa
注意:
- 生成使用的'xxxxx@company.com'和'xxxxx@126.com'并不一定是用邮箱,也可以用其他的字符串代替。现在很多教程都是用邮箱生成,实际上这只是生成SSH-Key的名称,仅为了增加辨识度,没有什么特殊含义。
- 生成时可能文件没有权限,导致出现以下错误:
解决方法:root权限或者直接在当前文件夹下建立Enter passphrase (empty for no passphrase): Enter same passphrase again: Saving key "~/.ssh/gitee_id_rsa" failed: No such file or directory
2. 将SSH-Key添加到平台上
首先,我们打开~/.ssh文件夹,可以看到刚刚生成的SSH-Key:
$ cd ~/.ssh
$ ls
目录如下:
.
├── company_id_rsa
├── company_id_rsa.pub
├── github_id_rsa
├── github_id_rsa.pub
查看~/.ssh/company_id_rsa.pub的文件内容,可以得到一个以ssh-rsa开头的字符串,复制public key:
$ cat ~/.ssh/company_id_rsa.pub
# ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDgtt25JYMfs4Z4p...
打开对应的代码平台,把刚刚复制的public key添加到仓库中即可。以gitLab为例:
打开User Settings->SSH Keys:
个人的SSH-Key也同此操作。
3. 本地配置SSH-Key管理文件
在~/.ssh文目录下新建文件config,添加如下内容:
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
# company
Host company.com
HostName company.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/company_rsa
Host和HostName添加服务器域名,IdentityFile添加对应的私钥路径。
4. 测试是否配置成功
我们可以用ssh的命令来测试是否成功:
$ ssh -T git@github.com
以github为例,成功会返回:
Hi xxx!You've successfully authenticated, but GitHub does not provide shell access.
如果遇到超时的问题:
ssh: connect to host xxx-company.com port 22: Connection timed out
可以尝试git clone拉一下代码,如果代码可以拉取,说明配置成功。
到此结束啦。