Git多个SSH Key共存解决方案

目前手上不止一个git账号,平台也不一致,这就比较尴尬了:

  1. 同一个SSH Key中不允许两个账号
  2. 再次生成新的SSH Key会将上次的覆盖

目前的解决办法是,生成多个SSH Key并命别名,通过配置文件指定域

用ssh-keygen生成多个key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ ssh-keygen -t rsa -C "wuwz@live.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/wuwenze/.ssh/id_rsa): /Users/wuwenze/.ssh/github
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ubuntu/.ssh/id_rsa_github.
Your public key has been saved in /home/ubuntu/.ssh/id_rsa_github.pub.
The key fingerprint is:
SHA256:T4s5hxOOX3ABGNHZNMPX6v7J1rgYxfzXMCuCipIh5Ng wuwz@live.com
The key's randomart image is:
+---[RSA 2048]----+
| o=.=+ . |
| . o.oo. . |
| .. . |
| . ..o |
|+. S o. * |
|o.E o @ ... =.|
| . o . O *.o .o+|
| o . o = ..=o.o|
| .. . . .o=. |
+----[SHA256]-----+

根据提示,重新指定文件名,假设我有三个平台需要同时管理,即

1
2
3
/Users/wuwenze/.ssh/github
/Users/wuwenze/.ssh/gitee
/Users/wuwenze/.ssh/coding

依次按照上述操作,添加3个ssh-key,生成后的文件位于~/.ssh

添加私钥

git自动把新生成的私钥写到known_hosts中

1
2
3
$ ssh-add ~/.ssh/github
$ ssh-add ~/.ssh/gitee
$ ssh-add ~/.ssh/coding

如果执行ssh-add时提示”Could not open a connection to your authentication agent”,可以现执行命令:

1
$ ssh-agent bash

然后再运行ssh-add命令,添加完成后,通过以下命令来验证:

1
2
3
4
5
# 可以通过 ssh-add -l 来确私钥列表
$ ssh-add -l

# 可以通过 ssh-add -D 来清空私钥列表,清空后重复上一步操作
$ ssh-add -D

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ vi ~/.ssh/config

# coding
Host coding.net
HostName coding.net
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_coding

# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github

# github
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_gitee

配置公钥并验证

依次登录对应的平台,配置SSH公钥,如:github





依次验证:

1
2
3
$ ssh -T git@github.com
$ ssh -T git@gitee.com
$ ssh -T git@git.coding.net

# Git, SSH

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×