错误:无法打开VM:“[datastore] myVM1 / myVM1.vmx”,未知文件后缀

时间:2012-08-29 06:54:37

标签: java vmware processbuilder

我在使用Java中的ProcessBuilder运行vmrun时遇到了很多困难。

我有一个这样的命令字符串:

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

当您运行上面的vmrun命令(没有Java)时,该命令将成功执行。但是使用Java,我收到了ff。错误:

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

代码如下:

   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) {}
   }

我在切换到ProcessBuilder之前使用了Runtime.exec()。我认为它与引号有关,所以我添加了cmd.replace,但显然这是一个不同的问题。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

当我了解到使用上述脚本时管道命令出现问题时,我正在使用ProcessBuilder。 Googling发现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来执行。