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

如何打印Jenkins作业详情 定位执行指定Shell脚本的作业

方案概述

完全可以通过Jenkins内置Groovy脚本能力遍历全量作业,提取包括Execute Shell执行命令、流水线脚本在内的全量配置,直接匹配目标Shell脚本的特征值即可快速定位到你要找的第二个作业,不需要额外安装插件。

操作步骤
  • 用管理员账号登录Jenkins,进入「系统管理」-「脚本命令行」页面
  • 将下方Groovy脚本粘贴到编辑框,把脚本中YOUR_TARGET_SCRIPT_NAME.sh替换为你要排查的被调用Shell脚本的名称(也可替换为脚本绝对路径、固定传参等唯一特征字符串,提升匹配准确率)
  • 点击运行即可输出所有匹配到的作业信息
import jenkins.model.Jenkins
import hudson.tasks.Shell
import com.cloudbees.hudson.plugins.folder.Folder
import org.jenkinsci.plugins.workflow.job.WorkflowJob

// 替换为你要查找的目标脚本特征值
def searchKey = "YOUR_TARGET_SCRIPT_NAME.sh"
def matchResult = []

// 递归遍历所有层级作业,兼容文件夹嵌套场景
def scanItems(itemList) {
    itemList.each { item ->
        if (item instanceof Folder) {
            scanItems(item.items)
            return
        }
        try {
            // 匹配自由风格作业的Execute Shell步骤
            if (item.builders) {
                def shellCommands = item.builders.findAll { it instanceof Shell }.collect { it.command }
                shellCommands.each { cmd ->
                    if (cmd.contains(searchKey)) {
                        matchResult << [
                            name: item.fullName,
                            url: "${Jenkins.instance.rootUrl}${item.url}",
                            content: cmd.trim()
                        ]
                    }
                }
            }
            // 匹配Pipeline类型作业的脚本内容
            if (item instanceof WorkflowJob && item.definition?.script) {
                def pipelineContent = item.definition.script
                if (pipelineContent.contains(searchKey)) {
                    matchResult << [
                        name: item.fullName,
                        url: "${Jenkins.instance.rootUrl}${item.url}",
                        content: "流水线脚本中命中特征值"
                    ]
                }
            }
        } catch (Exception e) {
            // 跳过无权限访问、格式异常的作业
        }
    }
}

scanItems(Jenkins.instance.items)

// 打印结果
println "===== 匹配到的作业列表 ====="
matchResult.each { res ->
    println "作业名:${res.name}"
    println "访问地址:${res.url}"
    println "命中内容:\n${res.content}\n------------------------"
}

if (matchResult.isEmpty()) {
    println "未匹配到相关作业,可尝试更换更精准的搜索关键词(比如脚本绝对路径、调用时的固定参数)"
}
补充说明
  • 脚本同时兼容自由风格作业、嵌套在文件夹内的作业、Pipeline流水线作业三类常见场景
  • 如果搜索结果包含你已经确认过的那个作业,剩下的条目就是你要找的第二个触发脚本的作业
  • 如果存在间接调用(比如作业A调用脚本B,脚本B再调用目标脚本),可以把搜索关键词替换为调用链路中唯一的固定特征值重新检索

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:45:43