gopher 們,如何配置多個 GitHub 賬號?
大家好,我是 polarisxu。
現在的開發,無論是日常工作還是參與開源,都離不開 Git。開源項目,大家通常使用 GitHub 或 Gitee,而工作中通常會自建 Git 服務,比如通過 GitLab、Gogs 等搭建。
爲了方便使用,一般大家會配置 SSH keys,通過 ssh 協議 pull/push 倉庫。
1、生成 ssh 密鑰
首先,我們需要生成 ssh 密鑰:(基於 mac,linux 類似,Windows 下找對應工具)
ssh-keygen -C "polaris@studygolang.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xuxinhua/.ssh/id_rsa):
出現的提示,使用默認值即可。命令執行完後,會生成 id_rsa 和 id_rsa.pub 文件,其中 id_rsa.pub 是公鑰,拷貝其中的內容配置到 GitHub 或 GitLab 之類的網站。比如 GitHub 是這裏:https://github.com/settings/ssh/new。
2、一個電腦兩個不同網站賬號
這是最常見的場景:一個業餘號(github),一個工作號(比如自建 gitlab)。因爲是不同網站,因此可以使用同一個郵箱。當然也可以是一個 github 賬號,一個 gitee 賬號,爲了方便,以下使用 github 和 gitee。
在 ~/.ssh
目錄下創建一個 config 文件,在其中添加如下內容:
host github
hostname github.com
Port 22
host gitee
hostname gitee.com
Port 22
這裏沒有指定 id_rsa,因爲默認讀取的就是它。
這樣,本地使用 GitHub 還是 Gitee 完全沒區別。
注意,需要使用 id_rsa.pub 分別在 GitHub 和 Gitee 添加 SSH Keys
當然,你也完全可以使用兩個不同的賬號,具體見下文。
3、一個電腦兩個 GitHub 賬號
因爲兩個 GitHub 賬號,自然不能使用同一個 ssh 密鑰,因此生成另外一個:
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa_gmail -C "polaris@gmail.com"
這會在 ~/.ssh
目錄生成 id_rsa_gmail 和 id_rsa_gmail.pub 兩個文件。
將 id_rsa.pub 和 id_rsa_gmail.pub 配置到對應的 GitHub 賬號。然後跟上文一樣,編輯 config 文件:
# github 賬號:polaris@studygolang.com
host github
hostname github.com
Port 22
User git
IdentityFile ~/.ssh/id_rsa
# github 賬號:polaris@gmail.com
host gmail-github
hostname github.com
Port 22
User git
IdentityFile ~/.ssh/id_rsa_gmail
config 是 ssh 的配置,詳細信息可以參考:https://daemon369.github.io/ssh/2015/03/21/using-ssh-config-file。
針對以上場景,在具體使用時,我們需要注意以下幾點:
-
默認會使用第一個賬號,要使用第二個賬號,需要設置該項目自己的 user.email 和 user.name
-
git clone 時,第二個賬號,地址得是類似這樣的:
git@gmail-github.com:studygolang/studygolang.git
如果有問題,可以執行以下兩個命令驗證:(記得替換爲你自己的配置)
$ ssh-add ~/.ssh/id_rsa_gmail
ssh -T git@gmail-github.com
4、總結
生活一個號,工作一個號。如果你沒有很好的區分,可以試試本文的方法,更愉快的 Coding!
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/G9F0qcCDwcR0AtyVW8CT_A