How to Poweroff a Virtual Machine using Oracle VirtualBox Java API?

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

I'm learnig to use VirtualBox Java API, but the documentation is not good.

My code:

VirtualBoxManager virtualBoxManager = VirtualBoxManager.createInstance(null);  IVirtualBox vbox = virtualBoxManager.getVBox(); List<IMachine> machines= vbox.getMachines();  for (IMachine m : machines) {     System.out.println("Name: " + m.getName() + " OS: " + m.getOSTypeId());     virtualBoxManager.startVm(m.getName(), null, 7000); //Starting a VM }  virtualBoxManager.cleanup();

How I stop a VM?

回答1:

import org.virtualbox_5_0.*;  public class VirtualboxVMStop {      public static void main(String[] args) {          String machineName = "Centos_1";         String url = "http://localhost:18083";         String user = "test";         String passwd = "test";          VirtualBoxManager mgr = VirtualBoxManager.createInstance(null);         mgr.connect(url, user, passwd);          // Get the virtual machine you need to connect to.         IVirtualBox vbox = mgr.getVBox();         IMachine machine = vbox.findMachine(machineName);          ISession session = null;         IProgress prog;          // Determine the status of the virtual machine.         MachineState state = machine.getState();         System.out.println(state);          if (MachineState.Running == state) {             session = mgr.getSessionObject();             machine.lockMachine(session, LockType.Shared);             prog = session.getConsole().powerDown();             prog.waitForCompletion(10000);             session.unlockMachine();         } else {             System.out.println(machineName+" is PoweredOff!");         }     } }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!