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

在Jenkins中获取触发任务的客户端IP/计算机名问题

获取Jenkins触发任务的客户端IP问题排查与解决

我需要获取用户触发Jenkins任务时所用客户端的IP/计算机名,试了下面这段Groovy脚本,但始终进不去内部的if判断:

import hudson.model.*
import static hudson.model.Cause.RemoteCause


def ipaddress=""
for (CauseAction action : currentBuild.getActions(CauseAction.class)) {

    for (Cause cause : action.getCauses()) {
        if(cause instanceof RemoteCause){
             ipaddress=cause.addr
             break;
        }
    }
}
return ["ip":ipaddress]

核心问题:触发方式不匹配

RemoteCause这个类型只在通过远程API触发任务(比如用curl调用Jenkins接口)时才会生成。如果是用户直接在Jenkins网页上点触发、定时任务自动跑、或者其他非API触发的场景,构建的Cause类型根本不是RemoteCause,自然不会进入那个if分支。

分场景解决方法

  • 网页UI触发:Jenkins默认不记录网页触发者的客户端IP,得装Request Capture Filter插件,它能捕获HTTP请求的客户端IP,之后在Pipeline里就能通过插件提供的Action获取。
  • 远程API触发:确认触发请求确实生成了RemoteCause,另外注意Jenkins新版本的API变化,原脚本里的currentBuild.getActions(CauseAction.class)可以改成更兼容的currentBuild.actions.findAll { it instanceof CauseAction }。
  • 定时/自动触发:这类场景本来就没有客户端IP,要提前判断,避免拿到空值。

兼容多场景的调整后脚本

import hudson.model.*
import org.jenkinsci.plugins.requestcapturefilter.RequestCaptureAction

def clientIp = ""

// 处理远程API触发的情况
currentBuild.actions.findAll { it instanceof CauseAction }.each { causeAction ->
    causeAction.causes.each { cause ->
        if (cause instanceof hudson.model.Cause.RemoteCause) {
            clientIp = cause.addr
            return // 找到就退出循环
        }
    }
}

// 处理网页UI触发的情况(需安装Request Capture Filter插件)
if (clientIp.isEmpty()) {
    def requestCapture = currentBuild.getAction(RequestCaptureAction)
    if (requestCapture) {
        clientIp = requestCapture.remoteAddr
    }
}

return ["client_ip": clientIp]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:42:10