多github帳號的SSH key切換
我有兩個github帳號,一個是個人所用,一個是為公司項目所用。如果是單用戶(single-user),很方便,默認拿id_rsa與你的github服務器的公鑰對比;如果是多用戶(multi-user)如user1,user2,那么就不能用在user2的身上了,這個時候就要配置一下了:
1、新建user2的SSH Key
#新建SSH key:
$ cd ~/.ssh # 切換到C:\Users\Administrator\.ssh
ssh-keygen -t rsa -C "mywork@email.com" # 新建工作的SSH key
# 設置名稱為id_rsa_work
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_work
2、新密鑰添加到SSH agent中
因為默認只讀取id_rsa,為了讓SSH識別新的私鑰,需將其添加到SSH agent中:
ssh-add ~/.ssh/id_rsa_work
如果出現Could not open a connection to your authentication agent的錯誤,就試着用以下命令:
ssh-agent bash
ssh-add ~/.ssh/id_rsa_work
3、修改config文件
在~/.ssh目錄下找到config文件,如果沒有就創建:
touch config # 創建config
然后修改如下:
我的config配置如下:
# 該文件用於配置私鑰對應的服務器
# Default github user(first@mail.com)
Host github.com
HostName github.com
User git
IdentityFile C:/Users/Administrator/.ssh/id_rsa
# second user(second@mail.com)
# 建一個github別名,新建的帳號使用這個別名做克隆和更新
Host github2
HostName github.com
User git
IdentityFile C:/Users/Administrator/.ssh/id_rsa_work
如果存在的話,其實就是往這個config中添加一個Host:
#建一個github別名,新建的帳號使用這個別名做克隆和更新
Host github2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa2
其規則就是:從上至下讀取config的內容,在每個Host下尋找對應的私鑰。這里將GitHub SSH倉庫地址中的git@github.com替換成新建的Host別名如:github2,那么原地址是:git@github.com:funpeng/Mywork.git,替換后應該是:github2:funpeng/Mywork.git.
4、打開新生成的~/.ssh/id_rsa2.pub文件,將里面的內容添加到GitHub后台。
可不要忘了添加到你的另一個github帳號下的SSH Key中。
5、測試:
Administrator@FANGPENG /e/work
$ ssh -T git@github.com
Hi BeginMan! You've successfully authenticated, but GitHub does not provide shel
l access.
Administrator@FANGPENG /e/work
$ ssh -T github2
Hi funpeng! You've successfully authenticated, but GitHub does not provide shell
access.
6、應用
測試成功,那么我嘗試在我的work目錄下克隆我@126.com賬號下的遠程倉庫。如下:
Administrator@FANGPENG /e/work
$ git clone github2:funpeng/Mywork.git
Cloning into 'Mywork'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
Checking connectivity... done
克隆成功,大功告成了!
感謝參考:
3.git.md