1

I'm having a lot of difficulty running vmrun through ProcessBuilder in Java.

I have a command string like this:

java -cp . RunTest 'vmrun -T esx -h https://10.123.236.123:443/sdk -u root -p password revertToSnapshot "[datastore] myVM1/myVM1.vmx" snapshot1'

When you run the vmrun command above (without Java), the command executes successfully. But with Java, I receive the ff. error:

Error: Cannot open VM: "[datastore] myVM1/myVM1.vmx", unknown file suffix

The code is below:

   public static void main(String args[]) {
      runProcessBuilderMulti(args[0]);
   }

   static void runProcessBuilderMulti (String cmd){
        List<String> list = new ArrayList<String>();
        System.out.println("Running Command: "+cmd.replace("\"","\\\""));

        Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(cmd);
        while (m.find())
                list.add(m.group(1));

        System.out.println(list);

        try {
                Process process = new ProcessBuilder(list).start();
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;

                while ((line = br.readLine()) != null) {
                        System.out.println(line);
                }

                System.out.println(process.exitValue());
        } catch (Exception e) {}
   }

I used Runtime.exec() before switching to ProcessBuilder. I thought it had to do with the quotes, so I added the cmd.replace, but apparently it was a different issue.

Any help would be appreciated. Thanks!

4

1 回答 1

1

当我了解到使用上述脚本的管道命令遇到问题时,我正在使用 ProcessBuilder。多谷歌搜索发现 ProcessBuilder 需要打开一个 shell 来执行某些命令。

ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l | grep daemon");

功能更新如下:

   static void runProcessBuilderMulti (String cmd){

        System.out.println("Running Command: "+cmd.replace("\"","\\\""));

        try {
                Process process = new ProcessBuilder("/bin/sh", "-c", cmd).start();
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;

                while ((line = br.readLine()) != null) {
                        System.out.println(line);
                }

                System.out.println(process.exitValue());
        } catch (Exception e) {}
   }

我猜更长的命令更难处理,比如管道命令,所以它需要自己的 shell 来执行。

于 2012-08-30T05:49:32.767 回答