You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins中含git clone的脚本通过withCredentials执行遇权限拒绝如何解决?

问题描述

我有一个包含git clone命令的脚本,已经通过Jenkins UI将SSH凭据存储在Jenkins凭据管理中,尝试用withCredentials组件包裹脚本执行来检出代码,但遇到权限拒绝错误。

我的代码示例:

withCredentials([sshUserPrivateKey(credentialsId: 'test', keyFileVariable: 'SSH_KEYFILE', passphraseVariable: '', usernameVariable: 'SSH_USERNAME')]) {
    sh 'git clone ssh://bitbucket.test.com:4444/test/test'
}

错误输出:

Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

解决方法

1. 让Git明确使用指定的SSH密钥文件

当前代码没有告知Git要使用withCredentials导出的SSH_KEYFILE私钥,Git会默认调用Jenkins agent上的默认SSH密钥(通常不存在或无权限),导致认证失败。修改sh命令,通过GIT_SSH_COMMAND环境变量指定私钥:

withCredentials([sshUserPrivateKey(credentialsId: 'test', keyFileVariable: 'SSH_KEYFILE', passphraseVariable: '', usernameVariable: 'SSH_USERNAME')]) {
    sh '''
        GIT_SSH_COMMAND="ssh -i $SSH_KEYFILE -o StrictHostKeyChecking=no" git clone ssh://bitbucket.test.com:4444/test/test
    '''
}
  • -o StrictHostKeyChecking=no用于避免首次连接时的主机密钥确认提示,若需要严格校验可移除该参数,但需提前在Jenkins agent上配置目标主机的密钥。

2. 验证凭据与权限的正确性

  • 确认Jenkins中存储的凭据IDtest无误,且该凭据对应的SSH公钥已添加到Bitbucket的用户SSH密钥或仓库部署密钥中:
    • 个人仓库:将公钥添加到你的Bitbucket账号设置的SSH密钥列表;
    • 团队仓库:添加为仓库的部署密钥(clone操作至少需要读权限)。
  • 检查git clone的SSH地址是否正确:确认主机地址、端口、仓库路径无拼写错误,Bitbucket的SSH端口是否确实为4444(默认是22,自定义端口需确保配置一致)。

3. 更简洁的方式:使用sshAgent组件

Jenkins提供的sshAgent组件可自动管理SSH密钥代理,无需手动指定密钥文件,适配多数场景:

sshAgent(['test']) {
    sh 'git clone ssh://bitbucket.test.com:4444/test/test'
}

该方式会自动将指定凭据的私钥加载到SSH代理中,Git会直接使用代理内的密钥完成认证。

内容的提问来源于stack exchange,提问作者newjenkinsuser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:41:10