Try   HackMD

一台電腦使用多個 Git 帳號 (SSH 金鑰)

前言

新公司專案感覺會時常使用 git,主要是想在若有緊急情況時,希望在家中也有辦法處理公司的事,剛好目前還在熟悉環境手邊暫時沒有排專案,就在公司電腦試了一下。

目標

在同一台電腦上,公司 github 帳號可以管理公司專案、私人 github 帳號可以管理私人專案

產生不同的金鑰

執行以下命令,Email 記得更換

$ ssh-keygen -t rsa -C "username@example.com"

接下來應該會跳出下方的訊息

Enter file in which to save the key (/Users/user/.ssh/id_rsa):

於訊息冒號後輸入金鑰名稱,輸入完後會跳出要你輸入驗證密碼的訊息,若不想設定按 Enter 跳過即可

Enter passphrase (empty for no passphrase): [輸入驗證密碼]
Enter same passphrase again: [再輸入一次同樣的驗證密碼]

因為我有兩個帳號,所以這個步驟會重複兩次,金鑰名稱分別為 id_rsa_company 和 id_rsa_personal

~/.ssh/id_rsa_company
~/.ssh/id_rsa_personal

查看目前管理的金鑰

$ ssh-add -l

因為我亂試了一段時間,列出來的金鑰有點混亂,所以我執行下方這段將舊的都先清除

$ ssh-add -D

將金鑰加入 ssh-agent

$ ssh-add ~/.ssh/id_rsa_company
$ ssh-add ~/.ssh/id_rsa_personal

最後再執行一次,看剛剛的金鑰是否有加入成功

$ ssh-add -l

修改 SSH Config

分別執行下面三段命令

$ cd ~/.ssh/
$ touch config
$ open config

config 打開後開始編輯內容

#公司帳號
Host github-company
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_company

#私人帳號
Host github-personal
	HostName github.com
	User git
	IdentityFile ~/.ssh/id_rsa_personal

Github 新增 SSH 金鑰

輸入下面指令可以複製公開金鑰的內容,再將它們貼回 Github 即可

pbcopy < ~/.ssh/id_rsa_personal.pub
pbcopy < ~/.ssh/id_rsa_company.pub

測試連線

輸入指令

$ ssh -T git@[輸入剛剛 config 內 Host 後方接的名稱]

依照前面的設定指令會是下面這樣

$ ssh -T git@github-company
$ ssh -T git@github-personal

成功的話應該會跳出下面的訊息

Hi [Username]! You've successfully authenticated, but GitHub does not provide shell access.

Clone repo 和 修改 Git config

執行下面命令就能將 repo clone 下來,私人專案在公司也能成功 push 上去

$ git clone git@github-personal:personal/project.git

若 repo 早已經 clone 下來的話,打開專案資料夾內 /.git/config 然後修改 [remote "origin"] 下方的 url 即可,範例如下

[remote "origin"]
	url = git@github-personal:personal/project.git
	fetch = +refs/heads/*:refs/remotes/origin/*

設定 User 資料

$ git config user.name "Brent Hsieh"
$ git config user.email "personal@example.com"

參考資料

https://gist.github.com/jexchan/2351996
https://medium.com/@hyWang/如何在一台電腦使用多個git帳號-907c8eadbabf
https://kejyuntw.gitbooks.io/ubuntu-learning-notes/content/network/network-multiple-ssh-key-to-same-github-site.html

tags: git ssh