在同一臺電腦上使用多個 SSH KEYS (GITHUB OR GITLAB)

404_NotFound發表於2017-12-19

1. 前言

很多時候,我們需要在自己的電腦上配置多個 ssh keys。比如個人的 github 和公司的 gitlab。折騰了很久,終於找到了一個說明清晰的文章,我嘗試著翻譯一下。

原文連結 Multiple SSH keys for different accounts on Github or Gitlab

2. 多個 github 賬號

  1. 建立 ssh-key,下面這條命令無需贅言
$ ssh-keygen -t rsa -C "your_name@home_email.com"
複製程式碼
  1. 輸入命令然後 enter 就行,接下來會出現這樣的提示
Generating public/private rsa key pair. 
Enter file in which to save the key (/home/user_name/.ssh/id_rsa):
複製程式碼

你可以自己取個名字,用以標識不同的賬號,比如 id_rsa_home。 也可以建立一個單路的資料夾來存放, 比如:/home/user_name/.ssh/home/id_rsa 。你也可以改成別的路徑。輸入完成後,繼續 enter,會提示設定短語(passphrase),這個我偷懶就直接 enter 了,沒有設定短語。

  1. 建立第二個 ssh-key,重複上面的步驟就可以了,只是在第 2 步的時候換一個名字或者路徑就可以了。
  2. 新增配置檔案
$ cd ~/.ssh/
$ touch config
$ nano config
複製程式碼

新增以下內容,都是固定格式,只需要更改 IdentifyFile 為對應的檔名或者路徑就可以了

# Home account
Host home.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_home

# Company account
Host company.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company
複製程式碼

然後刪除快取的 key

$ ssh-add -D
複製程式碼

如果提示一下內容

Could not open a connection to your authentication agent.
複製程式碼

你需要啟動 ssh-agent

eval `ssh-agent -s`
複製程式碼

重新執行上一條命令,然後可以通過以下命令檢查你的配置

$ ssh-add -l
2048 d4:e0:39:e1:bf:6f:e3:26:14:6b:26:73:4e:b4:53:83 /home/user/.ssh/id_rsa_home (RSA)
2048 7a:32:06:3f:3d:6c:f4:a1:d4:65:13:64:a4:ed:1d:63 /home/mateusz/.ssh/id_rsa_company (RSA)
複製程式碼

如果什麼都沒輸出,你需要執行以下命令(將後面的路徑更改為對應的路徑)

ssh-add ~/.ssh/id_rsa_company
ssh-add ~/.ssh/id_rsa_home
複製程式碼

最後,你可以愉快的測試你的 ssh-key 能否正常連線

$ ssh -T git@home.github.com
Hi home_user! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T git@work.github.com
Hi company_user! You've successfully authenticated, but GitHub does not provide shell access.
複製程式碼

3. github 和 gitlab

我個人就輸入這種情況,公司用的 gitlab,同時我要配置我自己的 github。同上面的配置檔案,主要是修改了 Host 配置項

# GITLAB
Host gitlab.company_url.com
HostName gitlab.company_url.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company

# GITHUB
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_home
複製程式碼

然後可以測試下

$ ssh -T git@gitlab.company_url.com
Welcome to GitLab, CompanyUser!

$ ssh -T git@github.com
Hi home_user! You've successfully authenticated, but GitHub does not provide shell access.
複製程式碼

相關文章