Ubuntu中git pull远程仓库时显示403错误

时间:2023-03-10 02:41:16
Ubuntu中git pull远程仓库时显示403错误

# 报错内容
fatal: unable to access 'https://git.dev.tencent.com/chendongnan/sfedu_wx.git/': The requested URL returned error: 403

# 问题起源
https方式每次都要输入密码,按照如下设置即可输入一次就不用再手输入密码的困扰而且又享受https带来的极速。

设置记住密码(默认15分钟):
`git config --global credential.helper cache`

如果想自己设置时间,可以这样做:
`git config credential.helper 'cache --timeout=3600'`这样就设置一个小时之后失效

长期存储密码 **(不推荐)**:
`git config --global credential.helper store`

**不推荐这种,因为这里保存的账号和密码保存到了`~/.git-credentials`文件中,它会自动应用到每一个git clone/pull指令,如果在服务器里面有多个项目,那么克隆的不是该账号下的项目,就只会得到403错误。**

# 报错原因
原因是`git config --global credential.helper store`这个命令可以将用户名和密码长期全局地长期地存储在客户端(实际是客户端所在电脑,并非git的任何目录下,也就是说,即使重装git,该用户名和密码也存在)。因为,这里保存的账号和密码会自动应用到每一个`git clone`或者`git pull` 指令,如果想要克隆的不是该账号下的项目,就只会得到403错误。

# 解决办法
## 方法一
在最开始增加远程地址的时候带上用户名和密码:
https://yourname:yourpassword@git.dev.tencent.com/name/project.git

比如我的是这样:
`git remote add origin https://chendongnan:cdn19981003@git.dev.tencent.com/chendongnan/sfedu_wx.git`

## 方法二
如果已经使用命令`git remote add origin https://git.dev.tencent.com/chendongnan/sfedu_wx.git`添加了远程仓库地址。

在`~`目录下的`.git-credentials`文件中添加如下内容:https://chendongnan:cdn19981003@git.dev.tencent.com

**步骤:**
- 进入根目录:`cd ~`
- 显示根目录下隐藏文件看有没有`.git-credentials`文件:`ls -a`
- 有则添加内容,无则先创建这个文件,进入编辑命令:`vim .git-credentials`,添加如下内容保存退出:https://chendongnan:cdn19981003@git.dev.tencent.com

## 方法三
运行命令:`rm ~/.git-credentials`,删掉`git config --global credential.helper store`保存的账号和密码。回到每次输入用户名和密码。