GitHub CLI执行gh repo clone时出现Permission denied (publickey)错误求助
我可以通过git clone https://github.com/rtyley/small-test-repo.git正常克隆仓库,但执行gh repo clone rtyley/small-test-repo时出现SSH权限拒绝错误:
Cloning into 'small-test-repo'... git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. failed to run git: exit status 128
执行gh auth status显示已正常登录,Git操作协议为SSH,令牌权限完整:
✓ Logged in to github.com account <my-github-account> (keyring) - Active account: true - Git operations protocol: ssh - Token: ghp_************************************ - Token scopes: 'admin:enterprise', 'admin:gpg_key', 'admin:org', 'admin:org_hook', 'admin:public_key', 'admin:repo_hook', 'admin:ssh_signing_key', 'audit_log', 'codespace', 'copilot', 'delete:packages', 'delete_repo', 'gist', 'notifications', 'project', 'repo', 'user', 'workflow', 'write:discussion', 'write:network_configurations', 'write:packages'
手动指定SSH密钥执行ssh -T git@github.com -i <github-pubkey-file>能成功验证身份,但多次执行gh auth logout再gh auth login仍无法解决问题,怀疑和多SSH身份文件有关。
1. 配置SSH强制使用指定密钥
编辑~/.ssh/config(Windows用户路径为C:\Users\<你的用户名>\.ssh\config),添加GitHub专属配置,强制使用对应密钥:
Host github.com HostName github.com User git IdentityFile ~/.ssh/<你的GitHub私钥文件名> IdentitiesOnly yes
IdentitiesOnly yes会阻止SSH自动尝试其他身份文件,避免多密钥冲突。
2. 临时切换gh的克隆协议为HTTPS
如果SSH问题暂时无法排查,可直接修改gh的Git操作协议为HTTPS,和你之前正常使用的克隆方式一致:
gh config set git_protocol https
之后再执行gh repo clone rtyley/small-test-repo即可正常克隆。
3. 校验gh关联的SSH密钥
查看gh当前绑定的SSH公钥指纹:
gh ssh-key list
对比该指纹与本地公钥文件的指纹(执行ssh-keygen -l -f ~/.ssh/<你的GitHub公钥文件名>.pub查看),确保两者一致。若不一致,重新添加正确的公钥到GitHub:
gh ssh-key add ~/.ssh/<你的GitHub公钥文件名>.pub --title "自定义标识标题"
4. 清除SSH代理缓存
若SSH代理缓存了旧身份,执行以下命令重置:
ssh-add -D ssh-add ~/.ssh/<你的GitHub私钥文件名>
完成后再次尝试gh repo clone命令。
内容的提问来源于stack exchange,提问作者silly-little-guy

