以前使用 git 經(jīng)常遇到這樣的問題:
項目A 位于 github 诚些,使用 ssh key A 提交代碼
項目B 位于 gitlab 新蟆,使用 ssh key B 提交代碼這樣本地就存儲了兩個私鑰滩报,在來回切換項目并提交代碼的時候怎么辦呢宝惰?
使用 ssh config 映射文件
在 ~/.ssh/
文件下創(chuàng)建 config
文件,內(nèi)容如下:
# github user
Host github.com
HostName github.com
User git
IdentityFile /Users/brandon/.ssh/id_rsa_github
# gitlab user
Host gitlab.com
HostName gitlab.com
User git
IdentityFile /Users/brandon/.ssh/id_rsa_gitlab
文件內(nèi)容格式:
標(biāo)簽 | 描述 |
---|---|
Host | 倉庫主機(jī),對應(yīng)具體項目下的.git/config 中的url 中的主機(jī)名 |
HostName | 倉庫主機(jī)名稱 |
User | 用戶名庇配,對于 git 來說就是固定值 git |
IdentityFile | ssh 私鑰 路徑 |
如上面描述的一樣斩跌,Host
對應(yīng)的是項目中的.git
目錄中config
文件中的遠(yuǎn)程倉庫url 的主機(jī)名,這樣可以解決一個問題:假如項目 A 和項目 C 都位于 github讨永,但是使用了不同的 ssh key 滔驶。
這種情況下可以使用如下配置:
- 項目 A 配置, 同上
- 項目 C 配置:
- 項目 C/.git/config
[remote "origin"] url = git@github2:brandon/project-c.git
- ~/.ssh/config
# github user
Host github.com
HostName github.com
User git
IdentityFile /Users/brandon/.ssh/id_rsa_github
Host github2
HostName github.com
User git
IdentityFile /Users/brandon/.ssh/id_rsa_github_2
# gitlab user
Host gitlab.com
HostName gitlab.com
User git
IdentityFile /Users/brandon/.ssh/id_rsa_gitlab
驗證 ssh key
使用如下命令可以驗證配置是否正確:
ssh -T github.com
補(bǔ)充
之前切換倉庫地址的時候經(jīng)常使用ssh-add
命令來添加私鑰,
假如從 github 切換到 gitlab
# 刪除 github 私鑰
ssh-add -d /Users/brandon/.ssh/id_rsa_gitlab.pub
# 添加 gitlab 私鑰
ssh-add /Users/brandon/.ssh/id_rsa_gitlab
但是有了 ssh config
文件之后就不用這么麻煩了卿闹。