在公司開發中,有時候會存在公司賬戶跟私人賬戶共存,並隨時需要切換的情況,這種情況下git可以配置多個ssh-key,無縫切換賬號。
假如有兩個github賬號,一個是私人github賬號,一個是公司github賬號
私人賬號:
- github用戶名:my
- email:[email protected]
公司賬號:
- github用戶名:company
- email:[email protected]
一、在用戶目錄下的.ssh目錄下生成祕鑰
與公鑰
如果用戶目錄下沒有.ssh
目錄,則需要新建一個
cd ~/.ssh
ssh-keygen -t rsa -f id_rsa_my
ssh-keygen -t rsa -f id_rsa_company
一路回車即可
- 注:國內很多博客都會帶上
-C "xxx郵箱"
這個參數,但其實-C
參數是用來做祕鑰註釋的,以便知道這個祕鑰到底是幹嘛的。填個郵箱進去可以當成是備註,但不是必須,你也可以填個我是世界首富
上面ssh-keygen
命令參數:
- -t: 指定生成
rsa
類型祕鑰 - -f: 指定生成祕鑰的名字,可以不指定該參數,默認就會生成2個文件:私鑰
id_rsa
,公鑰id_rsa.pub
。由於需要生成兩對私鑰公鑰,因此需要指定-f
,否則生成兩次後,私鑰公鑰會覆蓋
上面的命令調用完後會生成四個文件:
- id_rsa_my
- id_rsa_my.pub
- id_rsa_company
- id_rsa_company.pub
二、將公鑰
配置到對應的github賬號中
公鑰
即.pub
文件可以直接用文本打開,內容粘貼到github的 Settings -> SSH and GPG keys -> New SSH Key
,Title隨便起,自己能認出來即可,Key裏面填寫複製的.pub
裏的內容,這樣公鑰就配置好了
三、創建config文件
在.ssh
目錄下創建config
文件,git通過這個文件才知道哪個私鑰去對應哪個公鑰
touch config
config
文件內容:
# my
Host my
HostName github.com
IdentityFile ~/.ssh/id_rsa_my
# company
Host company
HostName github.com
IdentityFile ~/.ssh/id_rsa_company
config
文件部分參數含義,僅做記錄
# Host: 主機別名
# HostName: 託管平臺域名地址,如github.com
# IdentityFile: 該Host私鑰文件
# User: 託管平臺用戶名
# Port: 端口號,可不填(如果不是默認22號端口則需要指定)
# PreferredAuthentications publickey
四、測試ssh-key是否連通
ssh -T git@my
ssh -T git@company
成功的情況下會返回:
Hi xxx! You've successfully authenticated, but GitHub does not provide shell access.
此時私鑰
和 公鑰
都配置正常了
五、測試clone不同github倉庫
此時測試一下clone私人git倉庫,必須使用SSH
鏈接
SSH
鏈接格式爲:
[email protected]:用戶名/倉庫名.git
比如下面例子:
[email protected]:convict/my-repo.git
要clone這個倉庫,需要進行改動,應使用:
git clone git@my:convict/my-repo.git
即把github.com
換成my
,此時clone成功,同理需要clone公司賬戶下的倉庫,需要把github.com
換成company
即可
如果直接使用複製下來的鏈接git clone [email protected]:convict/my-repo.git
,會clone失敗:
Cloning into 'test'...
Warning: Permanently added the RSA host key for IP address '13.250.177.223' to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
解釋:
- 在SSH中,
@
與:
之間就是Host
,因此在git clone [email protected]:convict/my-repo.git
中,Host
就是github.com
,但在前面配置的config
文件中,指定了兩個Host
,分別爲my
與company
,而沒有一個加github.com
的Host!這是尤其需要注意的。 - 使用
git clone git@my:convict/my-repo.git
時,會在config
中找到一個值爲my
的Host,接着到其HostName
上找到與其私鑰
對應的公鑰
的倉庫地址。在本例中,就是根據其私鑰id_rsa_my
,在github.com
託管平臺上,匹配對應的公鑰
,然後匹配到convict/my-repo.git
這個倉庫。
六、單賬號ssh免密登錄
單賬號跟多賬號的操作步驟基本一致,但如果僅僅是一個賬號配置免密登錄,可以省略更多步驟,請看我的另一篇文章:
https://www.cnblogs.com/convict/p/14888283.html