gopher 們,如何配置多個(gè) GitHub 賬號(hào)?
閱讀本文大概需要 5 分鐘。
大家好,我是 polarisxu。
現(xiàn)在的開發(fā),無(wú)論是日常工作還是參與開源,都離不開 Git。開源項(xiàng)目,大家通常使用 GitHub 或 Gitee,而工作中通常會(huì)自建 Git 服務(wù),比如通過(guò) GitLab、Gogs 等搭建。
為了方便使用,一般大家會(huì)配置 SSH keys,通過(guò) ssh 協(xié)議 pull/push 倉(cāng)庫(kù)。
1、生成 ssh 密鑰
首先,我們需要生成 ssh 密鑰:(基于 mac,linux 類似,Windows 下找對(duì)應(yīng)工具)
ssh-keygen?-C?"[email protected]"
Generating?public/private?rsa?key?pair.
Enter?file?in?which?to?save?the?key?(/Users/xuxinhua/.ssh/id_rsa):
出現(xiàn)的提示,使用默認(rèn)值即可。命令執(zhí)行完后,會(huì)生成 id_rsa 和 id_rsa.pub 文件,其中 id_rsa.pub 是公鑰,拷貝其中的內(nèi)容配置到 GitHub 或 GitLab 之類的網(wǎng)站。比如 GitHub 是這里:https://github.com/settings/ssh/new。
2、一個(gè)電腦兩個(gè)不同網(wǎng)站賬號(hào)
這是最常見的場(chǎng)景:一個(gè)業(yè)余號(hào)(github),一個(gè)工作號(hào)(比如自建 gitlab)。因?yàn)槭遣煌W(wǎng)站,因此可以使用同一個(gè)郵箱。當(dāng)然也可以是一個(gè) github 賬號(hào),一個(gè) gitee 賬號(hào),為了方便,以下使用 github 和 gitee。
在 ~/.ssh 目錄下創(chuàng)建一個(gè) config 文件,在其中添加如下內(nèi)容:
host github
hostname github.com
Port 22
host gitee
hostname gitee.com
Port 22
這里沒(méi)有指定 id_rsa,因?yàn)槟J(rèn)讀取的就是它。
這樣,本地使用 GitHub 還是 Gitee 完全沒(méi)區(qū)別。
注意,需要使用 id_rsa.pub 分別在 GitHub 和 Gitee 添加 SSH Keys
當(dāng)然,你也完全可以使用兩個(gè)不同的賬號(hào),具體見下文。
3、一個(gè)電腦兩個(gè) GitHub 賬號(hào)
因?yàn)閮蓚€(gè) GitHub 賬號(hào),自然不能使用同一個(gè) ssh 密鑰,因此生成另外一個(gè):
$?ssh-keygen?-t?rsa?-f?~/.ssh/id_rsa_gmail?-C?"[email protected]"
這會(huì)在 ~/.ssh 目錄生成 id_rsa_gmail 和 id_rsa_gmail.pub 兩個(gè)文件。
將 id_rsa.pub 和 id_rsa_gmail.pub 配置到對(duì)應(yīng)的 GitHub 賬號(hào)。然后跟上文一樣,編輯 config 文件:
# github 賬號(hào):[email protected]
host?github
????hostname?github.com
????Port?22
????User?git
????IdentityFile?~/.ssh/id_rsa
# github 賬號(hào):[email protected]
host?gmail-github
????hostname?github.com
????Port?22
????User?git
????IdentityFile?~/.ssh/id_rsa_gmail
config 是 ssh 的配置,詳細(xì)信息可以參考:https://daemon369.github.io/ssh/2015/03/21/using-ssh-config-file。
針對(duì)以上場(chǎng)景,在具體使用時(shí),我們需要注意以下幾點(diǎn):
默認(rèn)會(huì)使用第一個(gè)賬號(hào),要使用第二個(gè)賬號(hào),需要設(shè)置該項(xiàng)目自己的 user.email 和 user.name git clone 時(shí),第二個(gè)賬號(hào),地址得是類似這樣的: [email protected]:studygolang/studygolang.git
如果有問(wèn)題,可以執(zhí)行以下兩個(gè)命令驗(yàn)證:(記得替換為你自己的配置)
$?ssh-add?~/.ssh/id_rsa_gmail
[email protected]
4、總結(jié)
生活一個(gè)號(hào),工作一個(gè)號(hào)。如果你沒(méi)有很好的區(qū)分,可以試試本文的方法,更愉快的 Coding!
