在Windows下配置多個Git提交賬戶

本文記錄在Windows下配置兩個github賬號的過程.


  1. 生成並部署SSH Key

安裝好Git客戶端後,打開git bash,輸入以下命令生成user1的SSH Key

ssh-keygen -t rsa -C "[email protected]"

在當前用戶的.ssh目錄下(C:\Users\lenovo\.ssh)會生成id_rsa私鑰文件和id_rsa.pub公鑰文件,將id_rsa.pub中的內容添加至user1的github中。然後在git bash中輸入以下命令測試該用戶的SSH密鑰是否生效:

ssh -T [email protected] 

注:若提示‘ssh: connect to host github.com port 22: Connection timed out’,證明遠端倉庫拒絕匿名認證。若連接成功則提示‘Hi user1! You’ve successfully authenticated, but GitHub does not provide shell access.’

接着生成user2的密鑰,注意不能再使用默認的文件名id_rsa,否則會覆蓋之前密鑰文件

ssh-keygen -t rsa -f ~/.ssh/id_rsa2 -C "[email protected]"

再將該用戶的公鑰文件添加至github中。測試user2的ssh連接時需要指定密鑰文件:

ssh -T [email protected] -i ~/.ssh/id_rsa2

  1. 配置config文件

在.ssh目錄下創建一個config文本文件,每個賬號配置一個Host節點。主要配置項說明

Host            別名
HostName        主機名
Port            端口
User            用戶名
IdentityFile    密鑰文件的路徑
IdentitiesOnly  只接受SSH Key 登錄
PreferredAuthentications publickey  強制使用Public Key驗證

# 配置user1 
Host u1.github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa
PreferredAuthentications publickey
User user1

# 配置user2
Host u2.github.com
HostName github.com
IdentityFile C:\\Users\\lenovo\\.ssh\\id_rsa2
PreferredAuthentications publickey
User user2

再通過終端測試SSH Key是否生效

ssh -T [email protected]
ssh -T [email protected]

  1. 配置用戶名及郵箱

如果之前配置過全局的用戶名和郵箱,可以按需選擇是否取消全局配置。若取消,需要在各倉庫下單獨配置相應的用戶名和郵箱;反之僅需在需要單獨用戶的倉庫下進行配置,未配置的倉庫按照全局配置獲取。

# 全局配置(任意位置執行)
$ git config --global user.name "github's Name"

$ git config --global user.email "[email protected]"

$ git config --list

# 取消全局配置
git config --global --unset user.name

git config --global --unset user.email

# 局部配置(在下載的項目根目錄執行)
$ git config user.name "gitlab's Name"

$ git config user.email "[email protected]"

注:配置加載的優先策略爲先執行局部配置讀取,再進行全局配置讀取


  1. 配置SSH認證私鑰
    通過puttygen工具(TortoiseGit)生成*.ppk文件,以支持pageant工具(TortoiseGit)認證私鑰

  1. 注意事項
    由於本人安裝了TortoiseGit,其默認SSH工具爲TortoiseGitPlink.exe,且配置了系統環境變量GIT_SSH指向TortoiseGitPlink.exe。在執行hexo d 指令時,默認該SSH工具進行鏈接,導致失敗。後刪除系統環境變量,且配置TortoiseGit的SSH工具爲Git下的\usr\bin\ssh.exe,解決提交錯誤的問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章