文章目录
1. 如何做到每次执行 Git 命令时,不需要每次都输入用户名和密码
https 方式每次都要输入密码,按照如下设置即可输入一次就可以很长时间不用再手输入密码
1.1 在远程地址中插入用户名和密码
示例:
https://linjinglei:y9S!)xxxxxxx(p6^IM1b@a.book.cc/source/xxx-ios.git
Param | Description |
---|---|
linjinglei | username |
y9S!)xxxxxxx(p6^IM1b | password |
https://a.book.cc/source/xxx-ios.git | remote_url |
- 将
remote_url
拆开,以https://
开头 username
和password
用:
拼接password
和remote_url
后半段用@
拼接
如果 username 中含有 @ 字符,需要将其转义为 %40
1.2 设置 git config 文件
首先执行下面的命令(如果不执行下面的命令,可能会导致设置无效)
git config --global user.name "linjinglei"
git config --global user.email "jinglei.lin@xxxx.com"
然后输入一次用户密码,再根据自己的需求执行下面的任意一条命令
1.2.1. 短时间存储(默认15分钟)
git config --global credential.helper cache
如果想自己设置时间,可以这样做:
git config credential.helper 'cache --timeout=3600'
这样就设置一个小时之后失效
1.2.2 长期存储密码
保存到磁盘
git config --global credential.helper store
保存到钥匙串(推荐)
git config --global credential.helper osxkeychain
首先执行上述命令,然后执行 Git 命令,此时会要求输入用户名和密码,输入之后再执行 Git 命令时,就不会再要求输入用户名和密码了。
如果设置了 osxkeychain 后发现执行 Git 命令依然报 403 的错误,很有可能是原来的钥匙串没有被删掉,务必检查一下钥匙串中老的密码是否删除了
store 和 osxkeychain 对比
2. 如何清除 Git 用户名和密码
2.1 修改 Git 密码后,执行报错
当我们修改了 Git 密码后,发现在终端执行 git clone
时会报 403
的错误,,并且只会报错,并不会给我们机会重新输入用户名和密码
unable to access ' https://a.book.cc/source/xxx-ios.git/ ': The requested URL returned error: 403
2.2 Git 用户名密码缓存原理
Git 用户名和密码的存储是通过 credential helper(凭证)
实现的
Git 去找系统中是否缓存了用户名和密码有三种策略:
- 缓存中找
- 磁盘中找
- 钥匙串中找
2.2.1 可以执行以下命令查看自己系统支持的 credential
git help -a | grep credential
得到结果:
credential remote-ext
credential-cache remote-fd
credential-cache--daemon remote-ftp
credential-osxkeychain remote-ftps
credential-store remote-http
2.2.2 执行以下命令查看 Git 全局配置
git config --list
得到结果
core.excludesfile=/Users/lynn/.gitignore_global
core.editor=emacs
difftool.sourcetree.cmd=opendiff "$LOCAL" "$REMOTE"
difftool.sourcetree.path=
mergetool.sourcetree.cmd=/Applications/Sourcetree.app/Contents/Resources/opendiff-w.sh "$LOCAL" "$REMOTE" -ancestor "$BASE" -merge "$MERGED"
mergetool.sourcetree.trustexitcode=true
user.name=linjinglei
user.email=jinglei.lin@xxxx.com
commit.template=/Users/lynn/.stCommitMsg
credential.helper=osxkeychain
其中 credential.helper=osxkeychain
是关键,需要将其删除
2.3 解决方案
2.3.1 打开 .gitconfig 文件
vi .gitconfig
得到结果
[core]
excludesfile = /Users/lynn/.gitignore_global
editor = emacs
[difftool "sourcetree"]
cmd = opendiff \"$LOCAL\" \"$REMOTE\"
path =
[mergetool "sourcetree"]
cmd = /Applications/Sourcetree.app/Contents/Resources/opendiff-w.sh \"$LOCAL\" \"$REMOTE\" -ancestor \"$BASE\" -merge \"$MERGED\"
trustExitCode = true
[user]
name = linjinglei
email = jinglei.lin@xxxx.com
[commit]
template = /Users/lynn/.stCommitMsg
[credential]
helper = osxkeychain
2.3.2 删除 credential 配置然后保存
[credential]
helper = osxkeychain
删除并保存后,再执行 Git 命令时就会发现让输入用户名和密码。
如果不想每次都输入,那么再参照 1.
里的方式配置就好了