git相信大家都在用,一般公司有一個賬號,放公司自己架的服務器中,員工自己還有一個github或者gitee的賬號,存放自己的一些私有代碼。本篇文章總結一下,本人在公司開發機上,使用多個git賬號的干貨,有需要的可以參考參考,避免采坑。
- 將以前設置的global name、email全部取消掉。
git config --global --unset user.name
git config --global --unset user.email - 刪除本機賬戶目錄下的.ssh目錄下的id_rsa以及id_rsa.pub
以windows為例 存放目錄為:

- 分別為公司git賬號以及私人git賬號生成ssh秘鑰
ssh-keygen -t rsa -C "公司賬號"
ssh-keygen -t rsa -C "私人賬號" - 不要一路enter 在提示輸入秘鑰名的地方 分別輸入 id_rsa_work id_rsa_gitee 這樣就會生成對應的秘鑰

- 添加私鑰
默認自動識別名為id_rsa的秘鑰,更名之后 需要自行手動添加
ssh-add ~/.ssh/id_rsa_work
ssh-add ~/.ssh/id_rsa_gitee
其中~為當前用戶目錄,也可以輸入絕對詳細路徑
如果添加的時候 報錯 "Could not open a connection to your authentication agent" 需要 執行以下命令
ssh-agent bash
然后再執行ssh-add上方的命令即可 - 創建config文件 為每個賬號添加服務地址

里面的內容
Host 公司git服務的ip地址
Port 公司git服務的端口號
HostName 自己取名字
PreferredAuthentications publickey
User git賬號
IdentityFile ~/.ssh/id_rsa_work
Host github.com
HostName github.com
PreferredAuthentications publickey
User 4896290004@qq.com
IdentityFile ~/.ssh/id_rsa_github
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
User 4896290004@qq.com
IdentityFile ~/.ssh/id_rsa_gitee
- 將ssh pub 秘鑰 放進 gitee 或者 gitlab 或者 github的ssh 配置中

