在Jenkins Groovy Pipeline中使用`Process`执行命令

时间:2019-06-21 01:55:53

标签: jenkins groovy

我正在使用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()无效是什么?我想念什么吗?

1 个答案:

答案 0 :(得分:0)

半年前,我遇到了类似的问题。我发现,使用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引擎在主机上