作者:知乎用戶
鏈接:https://www.zhihu.com/question/23028445/answer/416231632
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
git多賬號切換其實是有https的解決方案的,可以省去ssh配置公鑰相關的麻煩,不過安全性會降低,后面會提到。
比如你想用A賬號管理本地倉庫repoA,用B賬號管理本地倉庫repoB。
那么首先,看一下gloabal和system的config:
git config --global -l
git config --system -l
主要是看有沒有credential.helper把賬號密碼存起來了。因為https的url方式每次push的時候都要輸入密碼,比較麻煩,一般就會用credential.helper把賬號密碼存在global里了。這樣對單用戶沒問題,但多用戶時就會有問題。如果存的是A賬戶,那在repoB里push的時候肯定就會permission denied。所以看看global或者system哪個設置了保存就unset一下:
git config --global --unset credential.helper
git config --system --unset credential.helper
第二個命令可能需要權限吧。
接下來就是對本地倉庫的config設置了。比如進入本地倉庫repoA之后,看一下url:
git remote -v
https開頭的就是用的https了,git@ 開頭的就是用的ssh了,一般用瀏覽器打開github倉庫頁面之后在頁面里copy的都是https。一般是長這個樣子:
https://github.com/UserA/repoA.git
然后在https://和http://github.com之間加上用戶名@ ,用set-url設置就好:
git remote set-url origin https://UserA@github.com/UserA/repoA.git
當然默認是origin分支,要設置其他分支也一樣。@ 前的用戶名和倉庫權限的擁有者要對應起來。
改好之后,這時候push,就要輸入一下用戶A的密碼,然后就能push上去了。對於repoB也是一樣。每次push都需要輸入密碼了。那么為了避免麻煩,針對每一個本地倉庫,設置一下local的credential.helper:
git config --local credential.helper store
這樣賬號密碼就只針對當前倉庫保存,對其他倉庫沒有影響了。針對每一個需要管理的本地倉庫,都需要按以上步驟設置一次url和credential.helper,設置好之后,就能一直正常push了。
總結一下:
1. 清空global和system的credential.helper
2. 對每一個本地倉庫,設置一下url和local的credential.helper
關於安全性的問題,用git credentials存憑證的話,密碼是以明文形式存儲的,不論是git-credentials=store還是git-credentials=winstore(windows),git-credentials=osxkeychain(Mac),都有辦法直接看到密碼明文,除非用git-credentials=cache。當然也可以自定義,參考7.14 Git 工具 - 憑證存儲。