Git 設置多個賬號

 

清除原有全局設置

  • 這步不是必須的,如果你沒有使用

 

 git config --global user.name 'xxxxx' 
 git config --global user.email 'xxxx' 

設置過全局用戶名、email 等信息,則不用清除原有設置。(當然如果你也記不得了,那就這麼操作下吧)

  • 使用 git 命令取消全局設置

 

取消global
git config --global --unset user.name
git config --global --unset user.email



作者:ifjgm
鏈接:https://www.jianshu.com/p/cacf91579268
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

 

生成ssh 密鑰

  • 首先我們在~.ssh/ 文件夾下創建companygithub 文件夾,命令如下

 

mkdir company
mkdir github
  • 生成Gitlab 對應賬號的ssh密鑰,命令如下

 

ssh-keygen -t rsa -C "[email protected]"
  • 執行完上面的命令後,命令行會彈出如下提示

 

Enter file in which to save the key (/Users/tuoanlan/.ssh/id_rsa):
  • 輸入地址保存rsa 文件到指定路徑,如下(注意,我當前在.ssh 文件夾下,所以主意你指定的路徑是否正確)

 

 company/id_rsa_company
  • 然後會讓你輸入密碼的提示

 

Enter passphrase (empty for no passphrase):
  • 這裏一般不用輸入密碼,我們直接回車兩次(不輸入 passphrase
  • 當彈出如下提示

 

Your identification has been saved in company/id_rsrsa_company.
Your public key has been saved in company/id_rsrsa_company.pub.

說明ssh 密鑰已經生成並保存在 company 文件夾下 id_rsa_companyid_rsa_company.pub

二:將公鑰添加到網站

  • 複製公鑰,命令如下(當然你也可以手動複製)

 

pbcopy <id_rsa_company.pub
  • 粘貼 到ssh key 的框中,然後點擊 Add key 即可。如下圖所示

    image

  • 這裏僅僅以 Gitlab 爲例子,其他網站類似,不多贅述。

配置

  • .ssh 文件夾下創建 config 文件,並添加如下內容

 

# The git info for company
Host qdjr.git.zhudb.com                 # 寫公司git 地址
HostName qdjr.git.zhudb.com             # 寫公司git 地址
User git                                # 可以寫郵箱名稱,也可以寫 git 賬號
IdentityFile ~/.ssh/company/id_rsa      #對應公司 git 賬號密鑰路徑,注意不要寫錯

# The git info for github           
Host github.com                             # 寫 github 的地址
HostName github.com                         # 寫 github 的地址
User git                                    # 可以寫郵箱名稱,也可以寫 git 賬號
IdentityFile ~/.ssh/github/id_rsa_github    # 對應github 密鑰路徑,注意不要寫錯


以上內容只是示例,如果想直接複製後修改,請複製如下內容到 config

 

# The git info for company
Host  qdjr.git.zhudb.com
HostName  qdjr.git.zhudb.com
User [email protected]
IdentityFile ~/.ssh/company/id_rsa_company

# The git info for github
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github/id_rsa

把專用密鑰添加到 ssh-agent 的高速緩存中

執行命令 ssh-addIdentityFile 添加到 ssh-agent高速緩存中,執行如下命令

 

 ssh-add ~/.ssh/company/id_rsa_company 
 ssh-add ~/.ssh/github/id_rsa

驗證是否配置成功

  • 執行如下命令,驗證是否配置成功

 

 ssh -T [email protected]
  • 第一次執行可能會彈出如下提示

 

The authenticity of host 'qdjr.git.zhudb.com (121.43.184.183)' can't be established.
ECDSA key fingerprint is SHA256:BGEoBwmuXjA3mzMGnU2dxvpdlPv8pxBDZgA3SKOFMVs.
Are you sure you want to continue connecting (yes/no)? yes

  • 輸入 yes,提示如下

 

Warning: Permanently added 'qdjr.git.zhudb.com,121.43.184.183' (ECDSA) to the list of known hosts.
Welcome to GitLab, xxx!
  • 自此說明配置成功

總結

  • 首先我們建立了兩個不同的文件夾來存放不同的ssh key
  • 通過config ,指定不同的 git 賬號對應不同的 ssh key



作者:ifjgm
鏈接:https://www.jianshu.com/p/cacf91579268
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章