Search code examples
javacoldfusionrailo

Execute shell command with `java.lang.ProcessBuilder`


I wrote the following little script in CFML that executes a shell command, my problem is with the output, as long as the output is a single line is ok, if is multi-line I get only the first line, I tried to do a while loop on the script (commented on the code) but doesn't work and Java throws a memory error java.lang.OutOfMemoryError: Java heap space. What can I do?

<cfscript>
  str = ":>exec uname";
  exec_init=str.split(":>exec ");
  exec=exec_init[2].split(" ");
  p = createObject("java","java.lang.ProcessBuilder").init(exec).start();
  i = createObject("java","java.io.InputStreamReader").init(p.getInputStream());
  br = createObject("java","java.io.BufferedReader").init(i);
  line=br.readLine();
  //while (isDefined("line")) {
   //writeoutput(line);
  //}
  br.close();
  i.close();
</cfscript>

<cfdump var="#line#">

Output:

Linux

If I issue a command like

ls

with multi-line output I get e.g.

README.TXT

instead:

README.TXT VERSION.txt _-Railo-Getting-Started-_.html bin etc jre lib license-eplv10-aslv20.html modules notice.html resources start start.d start.ini start.jar stop webapps


Solution

  • Found the problem, I needed to add again line = br.readLine(); in my loop. Working code:

    <cfscript>
      str = ":>exec ls -al";
      exec_init=str.split(":>exec ");
      exec=exec_init[2].split(" ");
      p = createObject("java","java.lang.ProcessBuilder").init(exec).start();
      i = createObject("java","java.io.InputStreamReader").init(p.getInputStream());
      br = createObject("java","java.io.BufferedReader").init(i);
      line = br.readLine();
      while (isDefined("line")) {
       writeoutput(line);
       line = br.readLine();
      }
      br.close();
      i.close();
    </cfscript>