def startVM(vmname): from vboxapi import VirtualBoxManager mgr = VirtualBoxManager(None, None) vbox = mgr.getVirtualBox() name = vmname mach = vbox.findMachine(name) session = mgr.getSessionObject(vbox) progress = mach.launchVMProcess(session, "gui", []) progress.waitForCompletion(-1) mgr.closeMachineSession(session)
def stopVM(vmname): from vboxapi import VirtualBoxManager mgr = VirtualBoxManager(None, None) vbox = mgr.getVirtualBox() name = vmname mach = vbox.findMachine(name) session = mgr.getSessionObject(vbox) vboxConstants = mgr.constants mach.lockMachine(session, vboxConstants.LockType_Shared) console = session.console console.powerDown() session.unlockMachine()
def deleteVM(vmname): from vboxapi import VirtualBoxManager mgr = VirtualBoxManager(None, None) vbox = mgr.getVirtualBox() name = vmname vboxConstants = mgr.constants mach = vbox.findMachine(name) uuid = mach.id print("removing machine ", mach.name, "with UUID", uuid) # cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"]) disks = mach.unregister(vboxConstants.CleanupMode_Full) progress = mach.deleteConfig(disks)
def createVM(vmname, ostype): from vboxapi import VirtualBoxManager mgr = VirtualBoxManager(None, None) vbox = mgr.getVirtualBox() name = vmname vboxConstants = mgr.constants mach = vbox.createMachine("", name, [], ostype, "") # ubuntu_64 mach.memorySize = 2048 # hdd = vbox.createMedium("vdi", "", vboxConstants.constants.AccessMode_ReadWrite, vboxConstants.constants.DeviceType_HardDisk) mach.saveSettings() print("created machine with UUID", mach.id) vbox.registerMachine(mach)
class ManagedMgr: def __init__(self, vbox_user=None, vbox_pass=None, vbox_url=None, external_hc_ip=None, external_hc_port=None): self._vbox_url = vbox_url self._vbox_user = vbox_user self._vbox_pass = vbox_pass self.mgr = None self.vbox = None if self._vbox_url: self.mgr = VirtualBoxManager( "WEBSERVICE", { 'url': self._vbox_url, 'user': self._vbox_user, 'password': self._vbox_pass }) else: if os.name == 'nt': import pythoncom pythoncom.CoInitialize() self.mgr = VirtualBoxManager(None, None) try: self.vbox = self.mgr.getVirtualBox() except: logging.exception( "Cannot connect to VBOX. Check service is installed and running, and verify the user " "has valid credentials to access that service.") raise self._external_hc_ip = external_hc_ip self._external_hc_port = external_hc_port
class VirtualBoxImporter: DEFAULT_MACHINE_NAME = "Hack OS" DEFAULT_HDD_SIZE = gb_to_byte_size(60) DEFAULT_RAM_SIZE = 3072 DEFAULT_VRAM_SIZE = 128 def __init__(self, logger, image_path, name=None): self.logger = logger self._manager = VirtualBoxManager(None, None) self._vbox = self._manager.getVirtualBox() self._extension_pack_manager = self._vbox.extensionPackManager self._session = self._manager.mgr.getSessionObject(self._vbox) self._name = name or self.DEFAULT_MACHINE_NAME self._image_path = image_path def run(self, destroy_existing=True): if not self.check_valid_image(): self.logger.info("Image file at '%s' invalid or does not exist.", self.image_path) return machine = self.find_machine() if machine is not None: self.logger.info("Machine '%s' with name '%s' already exists.", machine.id, self.name) if destroy_existing: self.logger.info("Removing existing machine with name '%s'", self.name) self.remove_machine(machine) self.logger.info("Creating new machine with name '%s'", self.name) machine = self.create_machine() machine.memorySize = self.DEFAULT_RAM_SIZE machine.graphicsAdapter.VRAMSize = self.DEFAULT_VRAM_SIZE machine.graphicsAdapter.accelerate3DEnabled = True machine.graphicsAdapter.accelerate2DVideoEnabled = True machine.audioAdapter.enabled = True machine.audioAdapter.enabledIn = True machine.audioAdapter.enabledOut = True machine.BIOSSettings.IOAPICEnabled = True machine.clipboardMode = vboxapi_constant("ClipboardMode", "Bidirectional") machine.pointingHIDType = vboxapi_constant("PointingHIDType", "USBTablet") machine.RTCUseUTC = True medium = self.prepare_hack_medium() storage_controller = self.add_storage_controller(machine) ext_pack_names = [ e.name for e in self._extension_pack_manager.installedExtPacks ] if VIRTUAL_BOX_EXTENSION_PACK in ext_pack_names: self.add_usb_controller(machine) else: self.logger.warning( "USB 3.0 support not enabled. Install extension pack '%s'", VIRTUAL_BOX_EXTENSION_PACK) self.register_machine(machine) self.attach_device(machine, storage_controller, medium) def create_machine(self): try: machine = self._vbox.CreateMachine("", self.name, [], "Linux_64", "") except Exception as ex: self.logger.debug(ex) return None return machine def register_machine(self, machine): self._vbox.RegisterMachine(machine) def remove_machine(self, machine): full = vboxapi_constant("CleanupMode", "Full") mediums = machine.Unregister(full) machine.DeleteConfig(mediums) def find_machine(self): try: machine = self._vbox.FindMachine(self.name) except Exception as ex: self.logger.debug(ex) return None return machine def prepare_hack_medium(self): device_type = vboxapi_constant("DeviceType", "HardDisk") access_mode = vboxapi_constant("AccessMode", "ReadWrite") medium = self._vbox.OpenMedium(self.image_path, device_type, access_mode, False) medium.resize(self.DEFAULT_HDD_SIZE) return medium def add_storage_controller(self, machine): sata = vboxapi_constant("StorageBus", "SATA") controller = machine.AddStorageController("SATA Controller", sata) controller_type = vboxapi_constant("StorageControllerType", "IntelAhci") controller.controllerType = controller_type return controller def add_usb_controller(self, machine): usb_xhci = vboxapi_constant("USBControllerType", "XHCI") controller = machine.addUSBController("USB Controller", usb_xhci) return controller def attach_device(self, machine, controller, medium): IDE_port = 0 master_device = 0 device_type = vboxapi_constant("DeviceType", "HardDisk") with self.acquire_machine(machine) as session_machine: session_machine.AttachDevice(controller.name, IDE_port, master_device, device_type, medium) def check_valid_image(self): return self.image_path.endswith(".vdi") and os.path.exists( self.image_path) @contextmanager def acquire_machine(self, machine, save_settings=True): machine.LockMachine(self._session, vboxapi_constant("LockType", "Write")) try: yield self._session.machine finally: if save_settings: self._session.machine.SaveSettings() self._session.UnlockMachine() @property def name(self): return self._name @property def image_path(self): return self._image_path
def main(argv): usage = "usage: %prog --vm winXP -a 1 -p TCP -l 8080 -g 80 -P www" parser = OptionParser(usage=usage) parser.add_option( "-V", "--vm", action="store", dest="vmname", type="string", help="Name or UID of VM to operate on", default=None ) parser.add_option("-P", "--profile", dest="profile", type="string", default=None) parser.add_option("-p", "--ip-proto", dest="proto", type="string", default=None) parser.add_option("-l", "--host-port", dest="host_port", type="int", default=-1) parser.add_option("-g", "--guest-port", dest="guest_port", type="int", default=-1) parser.add_option("-a", "--adapter", dest="adapter", type="int", default=-1) (options, args) = parser.parse_args(argv) if not (parser.check_required("-V") or parser.check_required("-G")): parser.error("please define --vm or --guid option") if not parser.check_required("-p"): parser.error("please define -p or --ip-proto option") if not parser.check_required("-l"): parser.error("please define -l or --host_port option") if not parser.check_required("-g"): parser.error("please define -g or --guest_port option") if not parser.check_required("-a"): parser.error("please define -a or --adapter option") man = VirtualBoxManager(None, None) vb = man.getVirtualBox() print "VirtualBox version: %s" % vb.version, print "r%s" % vb.revision vm = None try: if options.vmname != None: vm = vb.findMachine(options.vmname) elif options.vmname != None: vm = vb.getMachine(options.vmname) except: print "can't find VM by name or UID:", options.vmname del man return print "vm found: %s [%s]" % (vm.name, vm.id) session = man.openMachineSession(vm.id) vm = session.machine adapter = vm.getNetworkAdapter(options.adapter) if adapter.enabled == False: print "adapter(%d) is disabled" % adapter.slot del man return name = None if adapter.adapterType == man.constants.NetworkAdapterType_Null: print "none adapter type detected" return -1 elif adapter.adapterType == man.constants.NetworkAdapterType_Am79C970A: name = "pcnet" elif adapter.adapterType == man.constants.NetworkAdapterType_Am79C973: name = "pcnet" elif adapter.adapterType == man.constants.NetworkAdapterType_I82540EM: name = "e1000" elif adapter.adapterType == man.constants.NetworkAdapterType_I82545EM: name = "e1000" elif adapter.adapterType == man.constants.NetworkAdapterType_I82543GC: name = "e1000" print "adapter of '%s' type has been detected" % name profile_name = options.profile if profile_name == None: profile_name = generate_profile_name(options.proto.upper(), options.host_port, options.guest_port) config = "VBoxInternal/Devices/" + name + "/" config = config + str(adapter.slot) + "/LUN#0/Config/" + profile_name proto = config + "/Protocol" host_port = config + "/HostPort" guest_port = config + "/GuestPort" vm.setExtraData(proto, options.proto.upper()) vm.setExtraData(host_port, str(options.host_port)) vm.setExtraData(guest_port, str(options.guest_port)) vm.saveSettings() man.closeMachineSession(session) del man
def main(argv): usage = "usage: %prog --vm winXP -a 1 -p TCP -l 8080 -g 80 -P www" parser = OptionParser(usage=usage) parser.add_option("-V", "--vm", action="store", dest="vmname", type="string", help="Name or UID of VM to operate on", default=None) parser.add_option("-P", "--profile", dest="profile", type="string", default=None) parser.add_option("-p", "--ip-proto", dest="proto", type="string", default=None) parser.add_option("-l", "--host-port", dest="host_port", type="int", default=-1) parser.add_option("-g", "--guest-port", dest="guest_port", type="int", default=-1) parser.add_option("-a", "--adapter", dest="adapter", type="int", default=-1) (options, args) = parser.parse_args(argv) if (not (parser.check_required("-V") or parser.check_required("-G"))): parser.error("please define --vm or --guid option") if (not parser.check_required("-p")): parser.error("please define -p or --ip-proto option") if (not parser.check_required("-l")): parser.error("please define -l or --host_port option") if (not parser.check_required("-g")): parser.error("please define -g or --guest_port option") if (not parser.check_required("-a")): parser.error("please define -a or --adapter option") man = VirtualBoxManager(None, None) vb = man.getVirtualBox() print "VirtualBox version: %s" % vb.version, print "r%s" % vb.revision vm = None try: if options.vmname != None: vm = vb.findMachine(options.vmname) elif options.vmname != None: vm = vb.getMachine(options.vmname) except: print "can't find VM by name or UID:", options.vmname del man return print "vm found: %s [%s]" % (vm.name, vm.id) session = man.openMachineSession(vm.id) vm = session.machine adapter = vm.getNetworkAdapter(options.adapter) if adapter.enabled == False: print "adapter(%d) is disabled" % adapter.slot del man return name = None if (adapter.adapterType == man.constants.NetworkAdapterType_Null): print "none adapter type detected" return -1 elif (adapter.adapterType == man.constants.NetworkAdapterType_Am79C970A): name = "pcnet" elif (adapter.adapterType == man.constants.NetworkAdapterType_Am79C973): name = "pcnet" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82540EM): name = "e1000" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82545EM): name = "e1000" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82543GC): name = "e1000" print "adapter of '%s' type has been detected" % name profile_name = options.profile if profile_name == None: profile_name = generate_profile_name(options.proto.upper(), options.host_port, options.guest_port) config = "VBoxInternal/Devices/" + name + "/" config = config + str(adapter.slot) + "/LUN#0/Config/" + profile_name proto = config + "/Protocol" host_port = config + "/HostPort" guest_port = config + "/GuestPort" vm.setExtraData(proto, options.proto.upper()) vm.setExtraData(host_port, str(options.host_port)) vm.setExtraData(guest_port, str(options.guest_port)) vm.saveSettings() man.closeMachineSession(session) del man
def main(argv): # # Parse command line arguments. # parse = OptionParser() parse.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="switch on verbose") parse.add_option("-a", "--autopath", dest="autopath", action="store_true", default=False, help="switch on autopath") parse.add_option("-w", "--webservice", dest="style", action="store_const", const="WEBSERVICE", help="connect to webservice") parse.add_option("-b", "--batch", dest="batch_file", help="script file to execute") parse.add_option("-c", dest="command_line", help="command sequence to execute") parse.add_option("-o", dest="opt_line", help="option line") global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd (options, args) = parse.parse_args() g_fVerbose = options.verbose style = options.style if options.batch_file is not None: g_fBatchMode = True g_fHasColors = False g_fHasReadline = False g_sScriptFile = options.batch_file if options.command_line is not None: g_fHasColors = False g_fHasReadline = False g_sCmd = options.command_line params = None if options.opt_line is not None: params = {} strparams = options.opt_line strparamlist = strparams.split(',') for strparam in strparamlist: (key, value) = strparam.split('=') params[key] = value if options.autopath: asLocations = [ os.getcwd(), ] try: sScriptDir = os.path.dirname(os.path.abspath(__file__)) except: pass # In case __file__ isn't there. else: if platform.system() in [ 'SunOS', ]: asLocations.append(os.path.join(sScriptDir, 'amd64')) asLocations.append(sScriptDir) sPath = os.environ.get("VBOX_PROGRAM_PATH") if sPath is None: for sCurLoc in asLocations: if os.path.isfile(os.path.join(sCurLoc, "VirtualBox")) \ or os.path.isfile(os.path.join(sCurLoc, "VirtualBox.exe")): print("Autodetected VBOX_PROGRAM_PATH as", sCurLoc) os.environ["VBOX_PROGRAM_PATH"] = sCurLoc sPath = sCurLoc break if sPath: sys.path.append(os.path.join(sPath, "sdk", "installer")) sPath = os.environ.get("VBOX_SDK_PATH") if sPath is None: for sCurLoc in asLocations: if os.path.isfile( os.path.join(sCurLoc, "sdk", "bindings", "VirtualBox.xidl")): sCurLoc = os.path.join(sCurLoc, "sdk") print("Autodetected VBOX_SDK_PATH as", sCurLoc) os.environ["VBOX_SDK_PATH"] = sCurLoc sPath = sCurLoc break if sPath: sCurLoc = sPath sTmp = os.path.join(sCurLoc, 'bindings', 'xpcom', 'python') if os.path.isdir(sTmp): sys.path.append(sTmp) del sTmp del sPath, asLocations # # Set up the shell interpreter context and start working. # from vboxapi import VirtualBoxManager oVBoxMgr = VirtualBoxManager(style, params) ctx = { 'global': oVBoxMgr, 'vb': oVBoxMgr.getVirtualBox(), 'const': oVBoxMgr.constants, 'remote': oVBoxMgr.remote, 'type': oVBoxMgr.type, 'run': lambda cmd, args: runCommandCb(ctx, cmd, args), 'machById': lambda uuid: machById(ctx, uuid), 'argsToMach': lambda args: argsToMach(ctx, args), 'progressBar': lambda p: progressBar(ctx, p), '_machlist': None, 'prompt': g_sPrompt, 'scriptLine': 0, 'interrupt': False, } interpret(ctx) # # Release the interfaces references in ctx before cleaning up. # for sKey in list(ctx.keys()): del ctx[sKey] ctx = None gc.collect() oVBoxMgr.deinit() del oVBoxMgr
import sys import os from time import gmtime, strftime from collections import namedtuple from workflow import Workflow try: from vboxapi import VirtualBoxManager from vboxapi.VirtualBox_constants import VirtualBoxReflectionInfo mgr = VirtualBoxManager(None, None) try: vbox = mgr.vbox except AttributeError: vbox = mgr.getVirtualBox() constants = VirtualBoxReflectionInfo(False) vbox_available = True except ImportError: vbox_available = False VMDetails = namedtuple('VMDetails', ['name', 'id', 'state', 'type']) currentVM = None def complete(wf): global currentVM vm_name = ' '.join(wf.args) vm_list = get_vm_list() if any(x.name == vm_name for x in vm_list): vm_details = None
def main(argv): from vboxapi import VirtualBoxManager # This is a VirtualBox COM/XPCOM API client, no data needed. mgr = VirtualBoxManager(None, None) # Get the global VirtualBox object vbox = mgr.getVirtualBox() print "Running VirtualBox version %s" % (vbox.version) # Get all constants through the Python manager code vboxConstants = mgr.constants # Enumerate all defined machines for mach in mgr.getArray(vbox, 'machines'): try: # Be prepared for failures - the VM can be inaccessible vmname = '<inaccessible>' try: vmname = mach.name except Exception, e: None vmid = '' try: vmid = mach.id except Exception, e: None # Print some basic VM information even if there were errors print "Machine name: %s [%s]" % (vmname, vmid) if vmname == '<inaccessible>' or vmid == '': continue # Print some basic VM information print " State: %s" % (enumToString( vboxConstants, "MachineState", mach.state)) print " Session state: %s" % (enumToString( vboxConstants, "SessionState", mach.sessionState)) # Do some stuff which requires a running VM if mach.state == vboxConstants.MachineState_Running: # Get the session object session = mgr.getSessionObject() # Lock the current machine (shared mode, since we won't modify the machine) mach.lockMachine(session, vboxConstants.LockType_Shared) # Acquire the VM's console and guest object console = session.console guest = console.guest # Retrieve the current Guest Additions runlevel and print # the installed Guest Additions version addRunLevel = guest.additionsRunLevel print " Additions State: %s" % (enumToString( vboxConstants, "AdditionsRunLevelType", addRunLevel)) if addRunLevel != vboxConstants.AdditionsRunLevelType_None: print " Additions Ver: %s" % (guest.additionsVersion) # Get the VM's display object display = console.display # Get the VM's current display resolution + bit depth + position screenNum = 0 # From first screen (screenW, screenH, screenBPP, screenX, screenY, _) = display.getScreenResolution(screenNum) print " Display (%d): %dx%d, %d BPP at %d,%d" % ( screenNum, screenW, screenH, screenBPP, screenX, screenY) # We're done -- don't forget to unlock the machine! session.unlockMachine()
def main(argv): from vboxapi import VirtualBoxManager # This is a VirtualBox COM/XPCOM API client, no data needed. mgr = VirtualBoxManager(None, None) # Get the global VirtualBox object vbox = mgr.getVirtualBox() print "Running VirtualBox version %s" %(vbox.version) # Get all constants through the Python manager code vboxConstants = mgr.constants # Enumerate all defined machines for mach in mgr.getArray(vbox, 'machines'): try: # Be prepared for failures - the VM can be inaccessible vmname = '<inaccessible>' try: vmname = mach.name except Exception, e: None vmid = ''; try: vmid = mach.id except Exception, e: None # Print some basic VM information even if there were errors print "Machine name: %s [%s]" %(vmname,vmid) if vmname == '<inaccessible>' or vmid == '': continue # Print some basic VM information print " State: %s" %(enumToString(vboxConstants, "MachineState", mach.state)) print " Session state: %s" %(enumToString(vboxConstants, "SessionState", mach.sessionState)) # Do some stuff which requires a running VM if mach.state == vboxConstants.MachineState_Running: # Get the session object session = mgr.getSessionObject() # Lock the current machine (shared mode, since we won't modify the machine) mach.lockMachine(session, vboxConstants.LockType_Shared) # Acquire the VM's console and guest object console = session.console guest = console.guest # Retrieve the current Guest Additions runlevel and print # the installed Guest Additions version addRunLevel = guest.additionsRunLevel print " Additions State: %s" %(enumToString(vboxConstants, "AdditionsRunLevelType", addRunLevel)) if addRunLevel != vboxConstants.AdditionsRunLevelType_None: print " Additions Ver: %s" %(guest.additionsVersion) # Get the VM's display object display = console.display # Get the VM's current display resolution + bit depth + position screenNum = 0 # From first screen (screenW, screenH, screenBPP, screenX, screenY, _) = display.getScreenResolution(screenNum) print " Display (%d): %dx%d, %d BPP at %d,%d" %(screenNum, screenW, screenH, screenBPP, screenX, screenY) # We're done -- don't forget to unlock the machine! session.unlockMachine()