【筆記】Source Tree 加入 SSH Key 的方法(適用 GitHub Enterprise)

前言

以下會簡單介紹 Source Tree 在 Windows 和 Mac 系統中產生和加入 SSH Keys 的方法,並綁定 Github,讓 GitHub Enterprise 帳戶也可以成功授權。

何謂 SSH Key

這邊的 SSH Key 概念,其實就是在 Github 平台設定好一組 Public Key(公鑰),每次透過 SSH 連線至 Github 時,Github 會認證你的裝置所設定好的 Private Key(私鑰),一旦公私鑰成功配對,則代表認證完成,你就擁有權限進入該 Github 帳號存取資源。所以不管是一般的 Github 帳號還是 Github Enterprise 帳號,其實概念都是一樣的。

產生 SSH Keys

Windows

1. Source Tree 選單列 Tools > Create or Import SSH Keys

2. 系統自動開啟 PuTTY Key Generator 視窗 > 點擊 [Generate] 按鈕。

3. 生成過程中,請不斷在 PuTTY Key Generator 視窗中移動你的滑鼠游標,這樣 PuTTY 才可以依照路徑生成獨立的 Key。這個過程大概耗時 1~2 分鐘。

4. 點擊 [Save public key] 與 [Save private key] 按鈕,將 Key 存在電腦裡。

5. 關閉 PuTTY Key Generator 視窗。

Mac

1. 使用 terminal 建立 SSH Keys:

$ ssh-keygen -t rsa -b 2048 -C "<example@mail.com>"
# 記得後面的 <example@mail.com> 要換成你自己的 email

2. 建立完成後,使用以下指令檢查 Keys 是否被建立好了:

$ ls ~/.ssh/
config		id_rsa		id_rsa.pub		known_hosts
  • config:設定檔,指定 ssh 連線到不同 host 時能夠用指定的 key 做認證。
  • id_rsa:Private Key
  • id_rsa.pub:Public Key
  • known_hosts:信任主機清單。

config 和 known_hosts 的設定會在下面提到。

Source Tree 加入私鑰

Windows

1. Source Tree 選單列 Tools > Launch SSH Agent…

2. 選擇你剛剛儲存的 Private Key 即可。

Mac

預設就會吃到 ~/.ssh/ 下的 configid_rsa 了,這時需要先對 config 指定 Github 要配對的 Private Key。

我自己對 Github Enterprise 的 config 的設定如下:

Host github.example.com
	User yourAccount@example.com
	PreferredAuthentications publickey
	IdentityFile /Users/<Your User Name>/.ssh/id_rsa
	UseKeychain yes
	AddKeysToAgent yes

# Host: Github Enterprise 網域,若是個人使用者就輸入 github.com
# User: Github Enterprise 帳號,一般是公司 email,若是個人使用者就輸入你的 Github 帳號
# PreferredAuthentications: 要驗證的對象,這邊統一都是打 publickey
# IdentifyFile: 你的 Private Key 位置

GitHub / GitHub Enterprise 加入公鑰

這部份就不分 Windows 或 Mac 了。

1. 進入 GitHub / GitHub Enterprise,點擊右上角自己的小頭像會出現下拉選單,點擊 <Settings> 進入設定頁面。

2. 點選左方的選單 Personal settings > SSH and GPG keys > 點擊 [New SSH key] 按鈕並將剛剛生成的 Public Key 貼上來儲存。

到這邊為止,SSH Key 就設定完成了!

但還差最後一步:信任主機連線,也就是上面提到過的 known_hosts

信任主機連線

第一次連線 SSH 到 Github 會被詢問是否要連線未知的主機,只要設定過一次,之後連線就不需再重新設定了。

Windows

1. 因為我們 Source Tree 是使用 PuTTY 進行 SSH 代理, 所以我們要先開啟 PuTTY.exe

2. 在 Host Name (or IP address) 欄位輸入你的 Github / Github Enterprise 網域。

3. 點選 [open] 按鈕。

4. 出現 PuTTY Security Alert,點擊 [Accept] 按鈕。

5. 出現 PuTTY terminal 並顯示 login as:,這樣就算設定成功囉!接下來就可以回到 Source Tree 繼續你的工作了。

Mac

1. Mac 使用者可輸入 ssh -T 指令:

$ ssh -T git@github.example.com
The authenticity of host 'github.com (IP ADDRESS)' can't be established.
RSA key fingerprint is SHA256:-----------------(馬賽克)-----------------.
Are you sure you want to continue connecting (yes/no)? 

# @ 後面的是你的 Github Enterprise 網域,若是個人使用者就輸入 github.com

2. 這時候就請輸入 yesknown_hosts 就會設定成功囉!接下來就可以回到 Source Tree 繼續你的工作了。

$ yes
Hi <Your Name>! You've successfully authenticated, but GitHub does not provide shell access.

大功告成

這樣所有設定就都完成了,可以不輸入帳號密碼就直接透過 SSH 使用 Github / GitHub Enterprise 內的專案了。

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments