本文記錄在Windows下配置兩個github賬號的過程。
(1)生成並部署SSH key
安裝好Git客戶端后,打開git bash,輸入以下命令生成user1的SSH Key:
ssh-keygen -t rsa -C "user1@email.com"
在當前用戶的.ssh目錄下會生成id_rsa私鑰文件和id_rsa.pub公鑰文件,將id_rsa.pub中的內容添加至user1的github中。然后在git bash中輸入以下命令測試該用戶的SSH密鑰是否生效:
ssh -T git@github.com
若連接成功則提示Hi user1! You've successfully authenticated, but GitHub does not provide shell access.
注:該命令僅限於文件名為id_rsa的密鑰。
接着生成user2的密鑰,注意不能再使用默認的文件名id_rsa,否則會覆蓋之前密鑰文件:
ssh-keygen -t rsa -f ~/.ssh/id_rsa2 -C "user2@email.com"
再將該用戶的公鑰文件添加至github中。
測試user2的ssh連接時需要指定密鑰文件:
ssh -T git@github.com -i ~/.ssh/id_rsa2
也可以使用ssh agent添加密鑰后進行測試。因為系統默認只讀取id_rsa,為了讓ssh識別新的私鑰,可以使用ssh-agent手動添加私鑰:
ssh-agent bash ssh-add ~/.ssh/id_rsa2
注:該方法僅限當前窗口有效,打開新的窗口則ssh連接失敗。
(2)配置config文件
在.ssh目錄下創建一個config文本文件,每個賬號配置一個Host節點。主要配置項說明:
Host 主機別名
HostName 服務器真實地址
IdentityFile 私鑰文件路徑
PreferredAuthentications 認證方式
User 用戶名
配置文件內容
# 配置user1 Host u1.github.com HostName github.com IdentityFile C:\\Users\\Administrator\\.ssh\\id_rsa PreferredAuthentications publickey User user1 # 配置user2 Host u2.github.com HostName github.com IdentityFile C:\\Users\\Administrator\\.ssh\\id_rsa2 PreferredAuthentications publickey User user2
再通過終端測試SSH Key是否生效
ssh -T git@u1.github.com ssh -T git@u2.github.com
(3)配置用戶名和郵箱
如果之前配置過全局的用戶名和郵箱,需要取消相關配置,再在各倉庫下配置相應的用戶名和郵箱。
git config --global --unset user.name git config --global --unset user.email
為各倉庫單獨配置用戶名和郵箱
git config user.name "user1" git config user.email "user1@email.com"
如果原先使用HTTPS通信,則需要修改遠程倉庫地址
git remote rm origin git remote add origin git@u1.github.com:xxx/xxxxx.git