首页 > 解决方案 > 在 Jenkins Groovy Pipeline 中使用“Process”执行命令

问题描述

我正在cURL使用sh命令执行命令,没有问题。

pulic uploadArtifct (String user, String password, String file, String 
  location) {
  def cred = "${user}:${password}"
  def cmd = "curl -v -u cred --upload-file ${file} ${location}"

  sh cmd

  }

但是,当我尝试cmd使用该Process对象执行相同的操作时。我收到一个错误:

public uploadArtifct (String user, String password, String file, String 
  location) {
  def cred = "${user}:${password}"
  def cmd = "curl -v -u cred --upload-file ${file} ${location}"
  try {
   def sout = new StringBuffer(), serr = new StringBuffer()
   def proc = cmd.execute()
   proc.consumeProcessOutput(sout, serr)
   proc.waitForOrKill(1000)
   println sout
  } catch (Exception e) {
    throw new RuntimeExceptipon("Cannot execute curl, exception: [${e.getClass().getName()} - '${e.getMessage()}']")
   }
  }

我看到的错误是:

java.lang.RuntimeException: Cannot execute curl, exception: [java.lang.RuntimeException - 'Error running; stdout='', stderr='curl: Can't open 'Folder/artifact/file.zip'!
curl: try 'curl --help' or 'curl --manual' for more information
'']

它是什么Process.execute()不起作用。我错过了什么吗?

标签: jenkinsgroovy

解决方案


半年前我也遇到过类似的问题。我发现,您使用 sh 命令运行的 curl 请求是在运行构建的代理上执行的。

sh cmd  //this runs on the agent and hence finds the ${file}

但是第二段代码

def proc = cmd.execute() . //This is run on the master and hence it cannot find the ${file}

当您使用 groovy 类时,它被设计为在主节点上执行。这是因为 Jenkins 使用的 groovy 引擎在 master 上


推荐阅读