一、準備工作
-
生成多對 SSH Key
-
為每個用戶(如“個人”、“公司”)生成一對獨立的 SSH Key。
-
示例(在 Git Bash 或 Linux 終端中執行):
# 個人 ssh-keygen -t rsa -b 4096 -C "personal@example.com" -f ~/.ssh/id_rsa_personal # 公司 ssh-keygen -t rsa -b 4096 -C "work@example.com" -f ~/.ssh/id_rsa_work
-
-
將公鑰添加到對應的 Git 服務器
- 登錄 GitHub/Gitee 等,將
~/.ssh/id_rsa_personal.pub
與~/.ssh/id_rsa_work.pub
分別添加到對應賬號的 SSH Keys 中。
- 登錄 GitHub/Gitee 等,將
二、統一 SSH 配置
編輯(或創建)SSH 配置文件,指明不同 Host 使用不同密鑰。
注意:Linux 下私鑰文件權限必須為
600
,目錄~/.ssh
必須為700
,否則 SSH 將拒絕加載密鑰。chmod 600 ~/.ssh/id_rsa_personal ~/.ssh/id_rsa_work chmod 700 ~/.ssh
在 ~/.ssh/config
(Windows 下為 C:\Users\<用戶名>\.ssh\config
)中添加:
# 個人賬號
Host github-personalHostName github.comUser gitIdentityFile ~/.ssh/id_rsa_personalIdentitiesOnly yes# 公司賬號
Host github-workHostName github.comUser gitIdentityFile ~/.ssh/id_rsa_workIdentitiesOnly yes
Host
為自定義主機別名,用于替代github.com
。IdentityFile
指向對應私鑰的絕對路徑。IdentitiesOnly yes
強制僅使用上述 Key。
三、Git 層面自動切換配置
3.1 全局 Git 配置打基礎
在任意環境下,都建議先在全局(~/.gitconfig
或 Windows %USERPROFILE%\.gitconfig
)設置“默認”身份,例如公司:
[user]name = 公司用戶名email = work@example.com
3.2 基于路徑的自動切換(Linux/Windows 均可)
Git 2.13+ 支持 includeIf
,可按目錄自動加載不同配置[1]。
-
創建個人配置文件
# ~/.gitconfig-personal [user]name = 個人用戶名email = personal@example.com
-
修改主配置
在~/.gitconfig
(或 Windows 上的%USERPROFILE%\.gitconfig
)末尾添加:[includeIf "gitdir:~/Code/personal/"]path = ~/.gitconfig-personal
-
gitdir:
后面須為對應目錄的絕對路徑,末尾加/
。 -
Windows 下也支持:
[includeIf "gitdir:C:/Users/用戶名/Code/personal/"]path = C:/Users/用戶名/.gitconfig-personal
-
保存后,進入該目錄內執行:
git config user.name # 應輸出“個人用戶名” git config user.email # 應輸出“personal@example.com”
-
四、克隆/設置遠程倉庫時使用 Host 別名
無論 Windows 還是 Linux,克隆或修改遠程 URL 時,將 github.com
替換為 github-personal
或 github-work
,與 ~/.ssh/config
中的保持一致:
# 個人項目
git clone git@github-personal:username/repo.git# 公司項目
git clone git@github-work: company/repo.git
如果項目已存在,可運行:
git remote set-url origin git@github-personal:username/repo.git
五、Windows 端額外說明
-
在 Git Bash 中按上述方法即可。
-
如果使用 PuTTY/Pageant:
- 將 OpenSSH 格式的私鑰轉換為 PPK:
puttygen id_rsa_personal -o id_rsa_personal.ppk
。 - 在 Pageant 中加載對應 PPK 文件。
- 修改項目的遠程地址同樣使用
github-personal
等別名。
- 將 OpenSSH 格式的私鑰轉換為 PPK:
六、常見問題與注意事項
-
私鑰權限過寬導致加載失敗
-
錯誤示例(Ubuntu):
Permissions 0664 for '/home/user/.ssh/id_rsa' are too open. This private key will be ignored.
-
需執行
chmod 600 ~/.ssh/id_rsa_*
[2]。
-
-
配置文件路徑中不要加雙引號
- 如
IdentityFile "~/.ssh/id_rsa"
可能無法被解析,宜寫作IdentityFile ~/.ssh/id_rsa
。
- 如
-
includeIf
版本兼容- Git ≥2.19 才支持在路徑中使用
~
。若出現問題請使用絕對路徑。
- Git ≥2.19 才支持在路徑中使用
-
驗證方式
ssh -T git@github-personal # 應返回“Hi <user>! You’ve successfully authenticated…” ssh -T git@github-work
七、參考資料
- Git 官方文檔:
git-config
中關于includeIf
的說明(鏈接) - CSDN 原文示例:按目錄自動切換 Git 用戶信息(鏈接)