git中多账号切换问题的解决方案(转)

时间:2023-03-09 17:08:58
git中多账号切换问题的解决方案(转)

作者:知乎用户
链接: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 工具 - 凭证存储