Skip to content
Coding

在同一台電腦上管理多個 GitHub 帳號:GitHub with SSH

我自己有兩個 GitHub 的帳號,一個是工作用的,一個是自己的。有時候自己做了一些小工具,想在工作用的電腦上調整的時候,都會因為個人的 repo 設定 private 而導致權限的關係被卡住,但又不想要每次修改時都去更新 global 的帳號,所以決定選擇使用 SSH 來做到同時使用兩個帳號這件事情。

What is SSH

Git SSH 金鑰是一組由公開金鑰(Public Key)和私密金鑰(Private Key)組成的加密憑證,用來在你本地電腦與遠端 Git 伺服器(如 GitHub、GitLab 等)之間建立安全的連線。

當我們使用 SSH 金鑰時,就不需要每次都透過帳號密碼進行身份的驗證,系統會自動用金鑰自行判斷,提升安全性與便利性。


Step. 1 建立 SSH Keys

# 工作帳號 
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519_work -N "" 
 
# 個人帳號 
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519_self -N ""
  • ssh-keygen:產生、管理及轉換 SSH 認證金鑰的指令工具
  • -t ed25519:指定要產生的金鑰類型
  • -C:為金鑰加上註解,通常用來標示金鑰用途或擁有者(例如你的工作信箱)。
  • -f ~/.ssh/id_ed25519_work:指定私鑰儲存的檔案名稱,公鑰會儲存為 ~/.ssh/id_ed25519_work.pub
  • -N "":設定私鑰的密碼(空字串代表不設密碼)

Step. 2 設定 SSH Config

建立 ~/.ssh/config 檔案:

Host github.com-work 
HostName github.com 
User git 
IdentityFile ~/.ssh/id_ed25519_work 
IdentitiesOnly yes 
 
Host github.com-personal 
HostName github.com 
User git 
IdentityFile ~/.ssh/id_ed25519_personal 
IdentitiesOnly yes
  • Host:定義一個主機別名,之後可以用這個名稱 github.com-work 來連線,而不是直接用 github.com
  • HostName:實際要連線的主機名稱,這裡是 GitHub 的主機
  • User:連線時使用的用戶名稱,GitHub SSH 連線時都用 git
  • IdentityFile:指定連線時要用的私鑰檔案
  • IdentitiesOnly:只使用這裡指定的金鑰,不會嘗試用其他金鑰

Step. 3 設定檔案權限

SSH 在驗證時會檢查 ~/.ssh/config 的權限,所以我們需要先把剛剛的 config 設定好權限:

chmod 600 ~/.ssh/config

Step. 4 設定 Git Conditional Includes

分別設定 .gitconfig-work 和 .gitconfig-self :

[user] 
    name = Work Account 
    email = [email protected]
[user] 
    name = Self Account 
    email = [email protected]

修改全域 Git 設定 ~/.gitconfig :

[user] 
    name = Global User 
    email = [email protected] 
 
[includeIf "gitdir:~/Git/Work/"] 
    path = ~/.gitconfig-work 
 
[includeIf "gitdir:~/Git/Self/"] 
    path = ~/.gitconfig-self

這樣設定的話,Git 就會在 ~/Git/Work/ 底下的專案用 [email protected] 進行 commit 和身份的驗證,在 ~/Git/Self/ 底下用 [email protected],而其他沒有指定的地方則是使用 [email protected]。

Step. 5 上傳 SSH Public Keys

首先查看 public keys:

cat ~/.ssh/id_ed25519_work.pub 
cat ~/.ssh/id_ed25519_self.pub

分別把印在 terminal 上的內容上傳到對應的 GitHub 帳號:Settings → SSH and GPG keys → 新增工作 key


使用方法

基本上和一般使用 Git 的方法沒什麼不同,只有在 clone repo 的時候要注意:要使用剛剛寫在 ~/.ssh/config 的 Host 取代原本的 github.com:

# 工作專案 
git clone [email protected]:company/project.git 
 
# 個人專案 
git clone [email protected]:username/project.git

這樣 Git 才會根據我們剛剛的設定用不同的 SSH 去做驗證。

如果你喜歡今天的分享,歡迎幫我拍個手讓我知道 👏🏻 以上就是今天的分享,我們下次見 👋🏻