同時使用:gitlab & github

china_zoushuang發表於2019-02-16

生成金鑰

gitlab 金鑰

ssh-keygen -t rsa -C "gitlab 使用者郵箱地址" ←┘
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa): ←┘
Enter passphrase (empty for no passphrase): ←┘
Enter same passphrase again: ←┘
...

github 金鑰

ssh-keygen -t rsa -C "github 使用者郵箱地址" ←┘
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa): id_rsa_github ←┘
Enter passphrase (empty for no passphrase): ←┘
Enter same passphrase again: ←┘
...

~/.ssh/ 目錄下生成以下檔案:

 - id_rsa
 - id_rsa.pub 
 - id_rsa_github
 - id_rsa_github.pub

分別將 id_rsa.pub 和 id_rsa_github.pub 內容複製到 gitlab 或 github 的 ssh key 中

新增 config 檔案

# gitlab
Host gitlab
    HostName gitlab.com
    IdentityFile ~/.ssh/id_rsa

# github
Host github
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_github

測試連線

gitlab

ssh -T git@gitlab.com ←┘
The authenticity of host `gitlab.com (52.167.219.168)` can`t be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes ←┘
...
Welcome to GitLab, username!

github

ssh -T git@github.com ←┘
The authenticity of host `github.com (52.167.219.168)` can`t be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes ←┘
...
Hi username! You`ve successfully authenticated, but GitHub does not provide shell access.

會在 ~/.ssh/ 目錄下自動生成 known_hosts 檔案

測試連線失敗,Permission denied (publickey).

原因是,我們自定義了 id_rsa_github 鑰匙名,預設情況下,連線會搜尋 id_rsa 鑰匙名,所以這裡會失敗
可以通過 ssh -T -v git@github.com 瞭解連線失敗的具體原因

ssh-agent

# 開啟 agent
eval $(ssh-agent -s) ←┘
Agent pid 8428
# 新增 鑰匙名
ssh-add ~/.ssh/id_rsa_github ←┘
Identity added: /c/Users/user/.ssh/id_rsa_github (/c/Users/user/.ssh/id_rsa_github)
# 檢視 agent list
ssh-add -l ←┘
8428 SHA256:A9UcJMadwTpF7TvsT5LEXsSssTs5qehmV9Q2Q8Ntw3o /c/Users/user/.ssh/id_rsa_github (RSA)
# 不用時可以關閉 agent
eval $(ssh-agent -k) ←┘
Agent pid 8428 killed

注意:使用github時,記得在自己的專案下定義 local user.name 和 local user.email

git config --local user.name ``
git config --local user.email ``

相關文章