1. 问题描述
从远程分支remote (code分支)向本地 (code分支) 拉取代码的时候,很顺利。但是从本地(code分支) 往远程(code分支) 推送的时候:
git push origin code:code
却报错如下:
Warning: Permanently added '[code.xxx.com]:1234' (ED4567) to the list of known hosts.
remote:
remote: ========================================================================
remote:
remote: The project you were looking for could not be found or you don't have permission to view it.
remote:
remote: ========================================================================
remote:
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
2. 问题分析
The project you were looking for could not be found or you don't have permission to view it.
这个是远程仓库拒绝访问的提示。但你说你可以成功拉取(git pull),那说明你的权限至少是有读权限的。然而 拉取权限 ≠ 推送权限.
此时我们链接的远程地址是:
[code.xxx.com]:1234
这个端口和域名看着是内部Git服务,比如GitLab或自建Git服务器。出现这个问题有可能:
- 配置了错误的SSH Key。
- 使用了错误的用户身份(比如用A账户的Key,访问B账户的仓库)。
- 远程仓库的权限策略不允许你push。
确认当前本地分支和远程分支关系
git branch -vv
origin ssh://git@code.xxx.com:1234/my_project.git (fetch)
origin ssh://git@code.xxxcom:1234/my_project.git (push)
确认远程仓库地址
git remote -v
* code 3dbd267 [origin/code: ahead 6] vlmevalkit
main 89e7ad7 [origin/main] add notes
从这里看出来,当前在code分支, 这个分支和远程的origin/code有关联, 本地比远程提前6个提交,说明本地有新提交,但还没push成功.
确定是在自己账号下的仓库吗?
ssh -T -p 1234 git@code.xxx.com
Welcome to GitLab, @Mike!
Oh, 我的本地环境(这台服务器)配置的 SSH Key,是属于 用户 Mike 的! 我拉代码的时候(git clone、git pull),其实是以 Mike 的身份在访问。我 push 的时候,GitLab会校验 Mike 对这个仓库(/my_project)有没有 push 权限。很可能Mike在这个项目里是Reporter或者没有push权限,所以 push 被拒绝。
3. 解决方案
切换到你自己的SSH Key. 你需要检查你自己的SSH Key(Daniel的)是否已经上传到GitLab,并配置到当前环境下。
# 生成自己的key
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_2
上传:在GitLab网页的【Settings】->【SSH Keys】里添加你的公钥(.pub文件)。如果你想让这个key长期生效,可以修改~/.ssh/config:
Host code.xxx.com
HostName code.xxx.com
Port 1234
User git
IdentityFile ~/.ssh/id_rsa_2
配置完成后,测试
ssh -T -p 1234 git@code.xxx.com
如果一切正常,会看到:
Welcome to GitLab, @Daniel!
这就表示你已经以Daniel身份登录了,Git Push等操作都会用这个身份。
接着就可以正常push了. git push origin code