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

Jenkins中SSH Agent插件故障时,如何通过SSH包装Shell命令?

Jenkins SSH Agent插件故障时的替代SSH认证方案

问题场景

Jenkins版本v2.375.1,原本使用SSH Agent插件实现SSH认证执行Git命令,示例代码:

sshagent(credentialsId: ["my-ssh-credentials"]) {
  sh """
    git tag some_tag
    git push origin some_tag
  """
}

但插件出现故障,执行时抛出错误:

+ which ssh-agent
/usr/bin/ssh-agent
[Pipeline] dir
Running in c:\jenkins\workspace\test\test-ssh
[Pipeline] {
[Pipeline] sshagent
[ssh-agent] Using credentials software.development@company.com (my-ssh-credentials)
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent]   Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
[ssh-agent] FATAL: Could not find a suitable ssh-agent provider
[ssh-agent] Diagnostic report
[ssh-agent] * Exec ssh-agent (binary ssh-agent on a remote machine)

以下是几种可行的替代方案:

方案1:手动配置Git SSH命令

通过Jenkins凭据管理取出SSH私钥文件,直接指定Git使用该密钥执行操作:

withCredentials([file(credentialsId: 'my-ssh-credentials', variable: 'SSH_KEY')]) {
  sh """
    chmod 600 \$SSH_KEY
    export GIT_SSH_COMMAND="ssh -i \$SSH_KEY -o StrictHostKeyChecking=no"
    git tag some_tag
    git push origin some_tag
  """
}

细节说明:

  • chmod 600保证私钥权限符合SSH安全要求,否则会被拒绝使用
  • StrictHostKeyChecking=no跳过主机密钥验证,生产环境可根据需求调整为ask或yes,也可提前将Git服务器公钥写入节点的known_hosts文件

方案2:使用SSH Pipeline Steps插件执行命令

如果已安装SSH Pipeline Steps插件,可直接通过插件封装的命令执行操作(适合远程服务器操作,本地Git操作优先选方案1):

sshCommand(
  remote: [
    host: '你的Git服务器地址',
    credentialsId: 'my-ssh-credentials',
    port: 22
  ],
  command: 'git tag some_tag && git push origin some_tag'
)

方案3:降级SSH Agent插件

找到插件历史版本中曾稳定运行的版本,在Jenkins插件管理界面中降级到该版本,暂时规避当前故障版本的问题。

方案4:注入私钥到环境变量并配置

将SSH私钥作为文本凭据取出,写入临时密钥文件后执行操作,完成后清理文件:

withCredentials([string(credentialsId: 'my-ssh-credentials', variable: 'SSH_PRIVATE_KEY')]) {
  sh """
    mkdir -p ~/.ssh
    echo "\$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    chmod 600 ~/.ssh/id_rsa
    # 可选:提前添加Git服务器公钥到known_hosts
    ssh-keyscan 你的Git服务器地址 >> ~/.ssh/known_hosts
    git tag some_tag
    git push origin some_tag
    # 清理临时密钥
    rm ~/.ssh/id_rsa
  """
}

注意:此方法会在Jenkins节点的~/.ssh目录写入密钥,务必执行清理步骤,避免敏感信息泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:33:10