Jenkins流水线sshPut操作认证失败问题求助
Jenkins sshPut Auth Fail 问题排查与解决
问题场景
已在Jenkins流水线中通过sshagent加载SSH密钥,且通过bash命令验证密钥可正常连接远程主机,HOST/BASE_DIR/APP_USER等变量输出均正确,但使用sshPut(来自SSH Steps插件)时仍出现Auth fail错误。
流水线核心代码:
stage('Deploy to Host') { steps { sshagent(credentials: ['dev-host-ssh-key']) { script { def remote = [:] remote.name = 'remote-host' remote.host = "$HOST" remote.user = "$APP_USER" remote.allowAnyHosts = true echo "HOST: ${remote.host}" echo "BASE_DIR: ${env.BASE_DIR}" echo "APP_USER: ${remote.user}" try { sshPut remote: remote, from: 'scripts/', into: "$BASE_DIR/$APP_USER/" } catch (Exception e) { echo "Error during sshPut: ${e.message}" } } } } }
错误日志关键信息:
17:00:24 Identity added: /var/org/jenkins/b12adfb/workspace/3536173/some-dir@tmp/private_key_94848422121.key ... 17:00:25 Error during sshPut: Auth fail ... 17:00:25 com.jcraft.jsch.JSchException: Auth fail
排查与解决方法
1. 直接在Remote配置中关联凭据(推荐)
SSH Steps插件的sshPut默认不会自动读取sshagent加载的密钥,需显式在remote配置中指定凭据ID,无需依赖sshagent:
stage('Deploy to Host') { steps { script { def remote = [:] remote.name = 'remote-host' remote.host = "$HOST" remote.user = "$APP_USER" remote.allowAnyHosts = true remote.credentialsId = 'dev-host-ssh-key' // 直接关联Jenkins凭据 echo "HOST: ${remote.host}" echo "BASE_DIR: ${env.BASE_DIR}" echo "APP_USER: ${remote.user}" try { sshPut remote: remote, from: 'scripts/', into: "$BASE_DIR/$APP_USER/" } catch (Exception e) { echo "Error during sshPut: ${e.message}" } } } }
2. 从sshagent中提取密钥传入Remote配置
如果必须使用sshagent,可以手动读取sshagent生成的临时密钥文件内容,传入remote的privateKey字段:
stage('Deploy to Host') { steps { sshagent(credentials: ['dev-host-ssh-key']) { script { // 查找sshagent生成的临时密钥文件 def keyFiles = findFiles(glob: '**/*.key') if (keyFiles.isEmpty()) { error "No SSH key file found in workspace" } def privateKeyContent = new File(keyFiles[0].path).text def remote = [:] remote.name = 'remote-host' remote.host = "$HOST" remote.user = "$APP_USER" remote.allowAnyHosts = true remote.privateKey = privateKeyContent // 传入密钥内容 echo "HOST: ${remote.host}" echo "BASE_DIR: ${env.BASE_DIR}" echo "APP_USER: ${remote.user}" try { sshPut remote: remote, from: 'scripts/', into: "$BASE_DIR/$APP_USER/" } catch (Exception e) { echo "Error during sshPut: ${e.message}" } } } } }
3. 验证SSH连接基础可用性
先使用sshCommand执行简单命令,确认remote配置的认证是否正常:
// 在sshPut前添加测试命令 sshCommand remote: remote, command: 'echo "SSH connection test success"'
如果该命令也返回Auth fail,则说明问题出在remote的认证配置上,需确认:
- 远程主机
$HOST的$APP_USER用户的~/.ssh/authorized_keys是否包含对应公钥 - Jenkins凭据中的私钥是否与远程主机公钥匹配
- 远程主机的SSH服务是否限制了Jenkins代理主机的IP访问
4. 升级SSH Steps插件
部分旧版本的SSH Steps插件与sshagent集成存在兼容性问题,尝试将插件升级至最新稳定版后重试。
内容的提问来源于stack exchange,提问作者Oxycash
相关产品推荐
相关产品推荐

