要在一臺電腦上配置兩個 GitHub 賬戶并使用兩個不同的 SSH 密鑰,可以按照以下步驟操作:
1. 生成 SSH 密鑰對
- 打開終端(Terminal)。
- 生成第一個 SSH 密鑰對:運行以下命令并按照提示操作。
ssh-keygen -t rsa -C "your_email@example.com"
在這里,"your_email@example.com" 應(yīng)替換為您的第一個 GitHub 賬戶的電子郵件地址。
- 生成第二個 SSH 密鑰對:運行以下命令并按照提示操作。
ssh-keygen -t rsa -f ~/.ssh/id_rsa_second -C "your_second_email@example.com"
在這里,"your_second_email@example.com" 應(yīng)替換為您的第二個 GitHub 賬戶的電子郵件地址。
2. 添加 SSH 密鑰到 SSH 代理
- 啟動 SSH 代理:
eval "$(ssh-agent -s)"
- 將第一個 SSH 密鑰添加到 SSH 代理:
ssh-add ~/.ssh/id_rsa
- 將第二個 SSH 密鑰添加到 SSH 代理:
ssh-add ~/.ssh/id_rsa_second
3. 將 SSH 密鑰添加到 GitHub 賬戶
- 復制第一個 SSH 密鑰的公鑰:
cat ~/.ssh/id_rsa.pub
將公鑰復制到第一個 GitHub 賬戶的 SSH 密鑰設(shè)置中。
- 復制第二個 SSH 密鑰的公鑰:
cat ~/.ssh/id_rsa_second.pub
將公鑰復制到第二個 GitHub 賬戶的 SSH 密鑰設(shè)置中。
4. 配置 SSH 主機別名(可選)
- 編輯
~/.ssh/config文件(如果沒有則創(chuàng)建):
touch config
nano ~/.ssh/c
- 在文件中添加以下內(nèi)容,以便為每個 GitHub 賬戶配置主機別名:
# First GitHub account
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
# Second GitHub account
Host second.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_second
配置說明:
-
Host:自定義別名,會影響git相關(guān)命令 -
HostName:真實的服務(wù)器地址(域名) -
User:之前配置的用戶名可以省略(xxx@xxx.com) -
PreferredAuthentications:權(quán)限認證(publickey,password publickey,keyboard-interactive)一般直接設(shè)為publickey -
IdentityFile:rsa文件地址
5. 測試 SSH 連接
- 測試第一個 GitHub 賬戶的 SSH 連接:
ssh -T git@github.com
如果出現(xiàn)Hi ****! You've successfully authenticated, but GitHub does not provide shell access.提示,說明我們的配置成功。
- 測試第二個 GitHub 賬戶的 SSH 連接:
ssh -T git@second.github.com
現(xiàn)在您應(yīng)該能夠同時使用兩個 GitHub 賬戶并通過各自的 SSH 密鑰進行身份驗證。
設(shè)備重啟后重連
ssh-add ~/.ssh/id_rsa_second
參考文檔
一臺電腦雙 GitHub 賬戶配置,同時兩個 SSH 密鑰
如何在同一電腦上生成配置多個ssh key 公鑰 私鑰(保姆級教程)
多個Git配置多個ssh密鑰
手把手教你一臺電腦配置兩個Git賬戶