def _open_vbox(mountpoint): if "vboxapi" not in sys.modules: return True _link_confdir(mountpoint, ".VirtualBox") _link_confdir(mountpoint, "VirtualBox VMs") _link_conffile(mountpoint, ".vbox-starter.conf") mgr = VirtualBoxManager(None, None) vbox = mgr.vbox vmx = mgr.getArray(vbox, 'machines') if len(vmx) > 0: if len(vmx) > 1: show_error( _("Multiple virtual machines were found on %s, don't know " "which one to start. Please start it manually.") % mountpoint) else: vm = vmx[0].name if ask_user( _("Start Virtual Machine?"), _("A virtual machine named \n%s\n was found. Do you want " "to start it?") % vm): try: subprocess.Popen(["/usr/bin/vbox-starter.sh", vm]) except: show_error( _("An error occured trying to start the virtual " "machine:\n%s") % sys.exc_info())
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
def remote_start_guest_machine(): """ Starts the virtual machine. If it was not running before, it waits 50 seconds for the system to boot up. """ mgr = VirtualBoxManager(None, None) vbox = mgr.vbox log_host(f"Running VirtualBox version {vbox.version}") machine = vbox.findMachine(commons.VM_NAME) session = mgr.getSessionObject(vbox) if machine.state == mgr.constants.all_values('MachineState')['Running']: log_host('VM is already running') elif machine.state == mgr.constants.all_values('MachineState')['PoweredOff'] or \ machine.state == mgr.constants.all_values('MachineState')['Saved']: # TODO split this condition progress = machine.launchVMProcess(session, 'gui', '') progress.waitForCompletion(-1) log_host('VM succesfully started') log_host('Waiting for boot') # Waiting till virtual machine is ready to accept SSH connection time.sleep(50) # TODO try ping else: machine_state = str(machine.state) raise RuntimeError('Unexpected virtual machine state')
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 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 VirtualBoxController : machineName = "android_x86" def __init__(self) : self.mgr = VirtualBoxManager(None,None) self.vbox = self.mgr.vbox def createMachine(self,userName) : exMachine = self.vbox.findMachine(self.machineName) result = self.vbox.createMachine("",self.machineName + "_" + userName,None,'Linux',"") #result.setSettingsFilePath(exMachine.settingsFilePath) print "'%s" %(result) def findMachine(self,machineNum) : try : mach = self.vbox.findMachine(self.machineName + "_" + machineNum) #mach = self.vbox.findMachine(self.machineName + "_" + userName) return mach except pywintypes.com_error : nMachine = MachineCreator() nMachine.createNewMachine(int(machineNum)) mach = self.vbox.findMachine(self.machineName + "_" + machineNum) #print "WRONG MACHINE NAME" return mach def checkAllMachines(self) : for machines in self.mgr.getArray(self.vbox,'machines') : print "Machine '%s' " %(machines.name) def getSession(self) : self.session = self.mgr.getSessionObject(self.vbox) def makeProcess(self,mach) : self.process = mach.launchVMProcess(self.session,"gui","") self.process.waitForCompletion(-1) def closeSession(self) : self.mgr.closeMachineSession(self.session) def connectVmSocket(self,vmIp,vmPort) : mVmSocket = VmSocket(vmIp,vmPort) mVmSocket.bindSocket() mVmSocket.aceeptVm() vmReturn = mVmSocket.waitVm() print "VmReturn " + vmReturn if "Vm_Boot_Complete" in vmReturn : return True else : return False
def calling(f, sha): """ Main interface of the module, expected to be called from outside to execute the analysis process """ style = "WEBSERVICE" myManager = VirtualBoxManager(style, None) if (not f or not sha): file = open("/home/zozanh/Desktop/fin.log", "wr+") file.close() ctx = { 'global': myManager, 'mgr': myManager.mgr, 'vb': None, 'const': myManager.constants, 'remote': myManager.remote, 'type': myManager.type, '_machlist': None, } connect(ctx, ["http://localhost:18083/", USERNAME, PASSWORD]) oMachine = machineByName(ctx, "prethesis") if startVm(ctx, oMachine, "gui", f, sha): disconnect(ctx, ("h2sandbox", )) return True else: disconnect(ctx, ("h2sandbox", )) return False
def vb_get_manager(): # This code initializes VirtualBox manager with default style # and parameters global _virtualboxManager if _virtualboxManager is None: _virtualboxManager = VirtualBoxManager(None, None) vbox = _virtualboxManager.vbox return vbox
def start(): mgr = VirtualBoxManager(None, None) vbox = mgr.vbox name = "SandBox" mach = vbox.findMachine(name) session = mgr.mgr.getSessionObject(vbox) progress = mach.launchVMProcess(session, "gui", "") progress.waitForCompletion(-1) sleep(120)
def prepare(): global DIRNAME if not os.path.isdir(DIRNAME): os.mkdir(DIRNAME) open(os.path.join(DIRNAME, 'stopped_machines'), 'w') lockdir() manager = VirtualBoxManager(None, None) vbox = manager.vbox session = manager.mgr.getSessionObject(vbox) return manager, vbox, session
def connect(self): cwd = os.getcwd() vbp = os.environ.get("VBOX_PROGRAM_PATH") if not vbp: if os.path.isfile(os.path.join(cwd, "VirtualBox")): vbp = cwd if os.path.isfile(os.path.join(cwd, "VirtualBox.exe")): vbp = cwd if vbp: os.environ["VBOX_PROGRAM_PATH"] = vbp sys.path.append(os.path.join(vbp, "sdk", "installer")) from vboxapi import VirtualBoxManager self.globl = VirtualBoxManager(self.style, None) self.mgr = self.globl.mgr self.vb = self.globl.vbox self.const = self.globl.constants self.remote = self.globl.remote self.type = self.globl.type
def prepareVBoxAPI(self): debugmsg(2, "LibVBoxUnattended::prepareVBoxAPI()") self.mgr = VirtualBoxManager(None, None) self.vbox = self.mgr.vbox self.session = self.mgr.mgr.getSessionObject(self.vbox) self.constants = self.mgr.constants self.VMpath = os.path.dirname( self.vbox.composeMachineFilename(self.VMname, '')) if not sys.platform == 'win32': self.VMpath = self.VMpath.replace( " ", "\ ") # work with spaces in folder and file names print "VMpath = %s" % self.VMpath
def power_on(): mgr = VirtualBoxManager(None, None) vbox = mgr.vbox name = "XP" mach = vbox.findMachine(name) session = mgr.mgr.getSessionObject(vbox) print(session) progress = mach.launchVMProcess(session, "gui", "") print(progress) progress.waitForCompletion(-1) console = session.console os.system("cd C:/Program Files/Oracle/VirtualBox/ && dir") os.system("cd C:/Program Files/Oracle/VirtualBox/ && VirtualBox.exe")
class VirtualBox(): # Hypervisor def __init__(self): self.mgr = VirtualBoxManager(None, None) self.vbox = self.mgr.vbox def getsession(self, vm): try: mach = self.vbox.findMachine(vm) session = self.mgr.getSessionObject(mach) mach.lockMachine(session, 1) return session except Exception, e: print e return "error"
def check(self): vbm = VirtualBoxManager('XPCOM', None) self.ctx = {'global': vbm, 'vb' : vbm.vbox, 'mgr' : vbm.mgr, 'const' : vbm.constants} try: self.mach = self.ctx['vb'].findMachine(self.vmname) self.uuid = self.mach.id logger.info('Using %s (uuid: %s)', self.mach.name, self.mach.id) return True except Exception as e: logger.exception('Cannot find registered machine: %s. Error: %s', self.vmname, e) return False
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 check(self): # # Set up the shell interpreter context and start working. # from vboxapi import VirtualBoxManager oVBoxMgr = VirtualBoxManager(None, None) self.ctx = { 'global': oVBoxMgr, 'vb': oVBoxMgr.vbox, 'const': oVBoxMgr.constants, 'remote': oVBoxMgr.remote, 'type': oVBoxMgr.type } vbox = self.ctx['vb'] if vbox is not None: try: print("Running VirtualBox version %s" % (vbox.version)) except Exception as e: printErr(self.ctx, e) if g_fVerbose: traceback.print_exc() self.ctx['perf'] = None # ctx['global'].getPerfCollector(vbox) else: self.ctx['perf'] = None self.ctx['perf'] = self.ctx['global'].getPerfCollector(self.ctx['vb']) self.mach = self.get_mach() if self.mach == None: perror('Cannot find the machine: %s' % self.machine) return False pinfo('Using %s (uuid: %s)' % (self.mach.name, self.mach.id)) pinfo('Session state: %s' % self.get_const( "SessionState", self.mach.sessionState)) pinfo('Machine state: %s' % self.get_const( "MachineState", self.mach.state)) return True
def check(self): try: from vboxapi import VirtualBoxManager except ImportError: perror('You need to install VirtualBox!') return False vbm = VirtualBoxManager(None, None) self.ctx = { 'global': vbm, 'const': vbm.constants, 'vb': vbm.vbox, 'mgr': vbm.mgr } # the machine name or id must be valid for m in self.get_mach(): if m.name == self.machine or m.id == self.machine: self.mach = m break if self.mach == None: perror('Cannot find the machine: %s' % self.machine) return False pinfo('Using %s (uuid: %s)' % (self.mach.name, self.mach.id)) pinfo('Session state: %s' % self.get_const("SessionState", self.mach.sessionState)) pinfo('Machine state: %s' % self.get_const("MachineState", self.mach.state)) status = self.mach.state return True
class Provider(BaseProvider): name = "virtualbox" parameters = [ ] style = None def __init__(self, config): self.globl = None @classmethod def get_defaults(cls): try: from vboxapi import VirtualBoxManager except ImportError: return {} return { "vbox": { "name": "vbox", "type": "virtualbox", } } def provide(self, machine): if not self.globl: self.connect() lookfor = machine["name"] machines = self.globl.getArray(self.vb, 'machines') for m in machines: if m.name == lookfor or m.id == lookfor: return VirtualMachine(machine, self, m) # FIXME: Would be nice to support this in future... #for m in machines: # if m.name == machine["base"] or m.id == machine["base"]: # base = VirtualMachine(self, {"name": machine["base"]}) # break #else: # raise SidekickError("Unable to find base '%s'" % machine['base']) vmdir = os.path.join(os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share')), "sidekick", "vbox") vmpath = os.path.join(vmdir, machine["name"], "%s.box" % machine["name"]) vdipath = os.path.join(vmdir, machine["name"], "%s.vdi" % machine["name"]) if not os.path.exists(vdipath): base_path = ImageRegistry().get_image(machine['base']) if os.path.isdir(base_path): vdis = glob.glob(os.path.join(base_path, "*.vdi")) if not vdis: raise SidekickError("%s is not a valid base image" % machine['base']) base_path = vdis[0] base = self.vb.openMedium(base_path, self.const.DeviceType_HardDisk, self.const.AccessMode_ReadOnly) target = self.vb.createHardDisk("vdi", vdipath) progress = base.cloneTo(target, self.const.MediumVariant_Standard, None) Progress(self.globl, progress).do() else: target = self.vb.openMedium(vdipath, self.const.DeviceType_HardDisk, self.const.AccessMode_ReadOnly) if not os.path.exists(vmpath): desired_ostype = machine.get("os-type", "Ubuntu_64") matching_ostype = [x for x in self.globl.getArray(self.vb, "guestOSTypes") if x.id.lower() == desired_ostype.lower()] if len(matching_ostype) == 0: raise SidekickError("Unable to find OS Type '%s'" % desired_ostype) m = self.vb.createMachine(vmpath, machine['name'], matching_ostype[0].id, "", False) m.addStorageController("IDE Controller", self.const.StorageBus_IDE) m.saveSettings() self.vb.registerMachine(m) with Session(self.globl, m) as s: s.machine.attachDevice("IDE Controller", 0, 0, self.const.DeviceType_HardDisk, target) s.machine.saveSettings() else: print "opening" m = self.vb.openMachine(vmpath) self.vb.registerMachine(m) return VirtualMachine(machine, self, m) def connect(self): cwd = os.getcwd() vbp = os.environ.get("VBOX_PROGRAM_PATH") if not vbp: if os.path.isfile(os.path.join(cwd, "VirtualBox")): vbp = cwd if os.path.isfile(os.path.join(cwd, "VirtualBox.exe")): vbp = cwd if vbp: os.environ["VBOX_PROGRAM_PATH"] = vbp sys.path.append(os.path.join(vbp, "sdk", "installer")) from vboxapi import VirtualBoxManager self.globl = VirtualBoxManager(self.style, None) self.mgr = self.globl.mgr self.vb = self.globl.vbox self.const = self.globl.constants self.remote = self.globl.remote self.type = self.globl.type def disconnect(self): self.mgr = None self.vb = None self.ifaces = None self.remote = None self.type = None if self.globl: self.globl.deinit() self.globl = None
def __init__(self) : self.mgr = VirtualBoxManager(None,None) self.vbox = self.mgr.vbox
def main(args): parser = OptionParser( prog="vdautomount", usage="%prog [options] machine-name-or-uuid mountpoint", version="%prog " + globals()["VERSION"]) parser.add_option("-p", help="path to vdfuse", type="string", default=globals()["VDFUSE_COMMAND"], metavar="vdfuse") parser.add_option("-r", help="readonly", action="store_true") parser.add_option("-g", help="run in foreground", action="store_true") parser.add_option("-v", help="verbose", action="store_true") parser.add_option("-d", help="debug", action="store_true") parser.add_option("-a", help="allow all users to read disk", action="store_true") parser.add_option("-w", help="allow all users to read and write to disk", action="store_true") parser.add_option( "-m", help= "specify which disk to mount, required if machine has more than one disk", type="int", default=-1, metavar="NUMBER") options, args = parser.parse_args(args=args) if len(args) != 2: parser.error("invalid machine specifier or mountpoint") spec = args[0] mountpoint = args[1] vbm = VirtualBoxManager(None, None) if not (os.access(mountpoint, os.R_OK | os.W_OK) and os.path.isdir(mountpoint)): parser.error("mountpoint cannot be accessed or is not a directory") try: machine = vbm.vbox.getMachine(spec) except: try: machine = vbm.vbox.findMachine(spec) except: parser.error("couldn't find machine \"%s\"" % spec) mediums = [x.medium for x in machine.getMediumAttachments() if x.type == 3] if len(mediums) == 1: medium = mediums[0] elif options.m != -1: medium = mediums[options.m - 1] else: ss = sys.stdout sys.stdout = sys.stderr print "Multiple disks on machine:" for index, medium in enumerate(mediums): print "%d:\tbase:\t%s" % (index + 1, medium.base.location) if medium.id != medium.base.id: print "\tsnap:\t%s" % medium.location sys.stdout = ss parser.exit( 2, "%s: specify the disk number with the -m option\n" % parser.get_prog_name()) paths = [] while True: paths.append(medium.location) if medium.parent: medium = medium.parent else: break paths.reverse() base = paths[0] diffs = paths[1:] if len(diffs) > 100: parser.error("too many levels of snapshots") args = [options.p] for option, value in options.__dict__.iteritems(): if option in ("p", "m"): continue if value: args.append("-" + option) args.append("-f") args.append(base.encode("UTF-8")) for x in diffs: args.append("-s") args.append(x.encode("UTF-8")) args.append(mountpoint) try: os.execvp(options.p, args) except OSError as e: parser.error("error running vdfuse. wrong path (-p) ?")
class Manager(VirtualBoxManager): def __init__(self): ### initialize a session with virtual box self.mgr = VirtualBoxManager(None, None) self.vbox = self.mgr.vbox self.session = self.mgr.mgr.getSessionObject(self.vbox) self.package_base = "%s/%s" % (os.path.dirname(os.path.realpath(__file__)).rsplit('/',1)[0],'packages') def api_version(self): return self.vbox.APIVersion def get_machine(self,name): """ find a machine if it exists on the vbox """ try: machine = self.vbox.findMachine(name) return machine except: return None def get_machines(self): machines = self.mgr.getArray(self.vbox, 'machines') if machines: return machines return None def get_machine_names(self): names = [] machines = self.mgr.getArray(self.vbox, 'machines') if machines: for machine in machines: names.append(machine.name) return names return None def has_machine(self,name): machine = self.get_machine(name) if machine: return True return False def get_machine_info(self,name): machine = self.get_machine(name) if machine: info = {'name' :str(name), #'id' :str(machine.id), 'OSTypeID' :str(machine.OSTypeId), 'memorySize':str(machine.memorySize), 'state' :str(machine.state), 'sessionState':str(machine.sessionState) #'settingsFilePath':str(machine.settingsFilePath), #'getExtraDataKeys':str(machine.getExtraDataKeys()) } for key in machine.getExtraDataKeys(): if 'HostPort' in key: info['HostPort']=str(machine.getExtraData(key)) return info return '' def send_command(self,host,port,cmd): connect = Connect(host,'root','a',port,timeout=300) try: return connect.write(cmd) except: return {'fatal':True} def port_owner(self,port): machines = self.get_machines() for machine in machines: info = self.get_machine_info(machine) if info.get("HostPort") == port: return info.get("name") return {'error':True} def new_ssh_port(self,port): """ mechanism to provide a un-used ssh port """ machines = self.get_machines() if machines: for machine in machines: machine_info = self.get_machine_info(machine.name) for key, value in machine_info.iteritems(): #print "%s : %s" % (key,value) if key == 'HostPort': if int(value) == port: return self.new_ssh_port(port+1) else: return port return port def create_package(self,name,package_name): machine = self.get_machine(name) if machine: #package_base = "%s/%s" % (os.path.dirname(os.path.realpath(__file__)).rsplit('/',1)[0],'packages') print "\n creating drone package..." package_dir = "%s/%s" % (self.package_base,package_name) drone_cfg = "%s/drone.yml" % (package_dir) machine_path = machine.settingsFilePath.rsplit('/',1)[0] disk_name = None disk_path = None if os.path.exists(package_dir): shell("rm -rf %s" % (package_dir)) if not os.path.exists(package_dir): os.makedirs(package_dir) for file in os.listdir(machine_path): # find the disk if '.vdi' in file: disk_name = file disk_path = "%s/%s" % (machine_path,disk_name) if not os.path.exists(disk_path):# make sure the disk exists print 'Unable to find disk file' return None src = disk_path package_name_disk = "%s.vdi" % package_name dst = "%s/%s" % (package_dir,package_name_disk) print "\ncloning disk..." try: clonehd_code = shell("VBoxManage clonehd '%s' '%s' --format VDI" % (src,dst),strict=True) except Exception as e: print str(e) print "\n --note Make sure the vm is off" os.sys.exit(1) #if not os.path.exists(dst): # shutil.copyfile(src,dst) # copy the disk into package if not os.path.exists(drone_cfg): with open(drone_cfg,'w') as drone_file: machine_info = self.get_machine_info(name) machine_info['name']=package_name yaml.dump(machine_info, drone_file,default_flow_style=False) output = shell("tar czf %s.drone -C %s/ %s" % (package_dir,self.package_base,package_name)) if output.get('code')==0: shell("rm -rf %s" % (package_dir)) print "\ndrone package created" else: print "Error creating drone package" def init_package(self,name): cwd = os.getcwd() os.chdir(self.package_base) machine_info = {} drone_pkg_path = "%s/%s.drone" % (self.package_base,name) drone_path = "%s/%s" % (self.package_base,name) drone_yml_path = "%s/%s" % (drone_path,"drone.yml") drone_disk_path= "%s/%s.vdi" % (drone_path,name) if os.path.exists(drone_pkg_path): print "\nunpacking drone package..." shell("tar -zxvf %s" % (drone_pkg_path),shell=True) else: print 'Error drone package not found %s' % drone_pkg_path return False drn_yaml = None os.chdir(cwd) if os.path.exists(drone_yml_path): with open(drone_yml_path, 'r') as cfg: drn_yaml = yaml.load(cfg) else: print "Error unable to find drone.yml file in package %s" % drone_yml_path return False if os.path.exists(drone_disk_path): if drn_yaml: drn_yaml['memorySize']=int(drn_yaml.get('memorySize')) drn_yaml['OSTypeID']= drn_yaml.get('OSTypeID') drn_yaml['hard_disk_path']=drone_disk_path drn_yaml['network_adapter']=1 drn_yaml['network_enabled']=True drn_yaml['network_connected']=True drn_yaml['guest_ssh_port']='22' drn_yaml['host_ssh_port']=str(self.new_ssh_port(2223)) for k,v in drn_yaml.iteritems(): print "%s : %s" % (k,v) machine = Machine(drn_yaml) print "\nlaunching virtual machine %s..." % drn_yaml.get('name') print machine.create() shell("rm -rf %s" % (drone_path)) else: print "Error unable to find drone disk file %s" % (drone_disk_path) return False return True
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 __init__(self, vm_name, vidDevName=None): self.vm_name = vm_name self.mouse_btns = 0x00 # This is a VirtualBox COM/XPCOM API client, no data needed. self.wrapper = VirtualBoxManager(None, None) # Get the VirtualBox manager mgr = self.wrapper.mgr # Get the global VirtualBox object vbox = self.wrapper.vbox print("Running VirtualBox version %s" % (vbox.version)) # Get all constants through the Python wrapper code self.vboxConstants = self.wrapper.constants self.mach = vbox.findMachine(vm_name) # Get the session object self.session = mgr.getSessionObject(vbox) #If the machine is already Running if self.mach.state == self.vboxConstants.MachineState_Running: # Lock the current machine (shared mode, since we won't modify the machine) self.mach.lockMachine(self.session, self.vboxConstants.LockType_Shared) #Else, we have to launch the machine first else: progress = self.mach.launchVMProcess(self.session, "headless", "") progress.waitForCompletion(-1) # Our session object is ready at this point, the machine is already locked # since we launched it ourselves if self.mach.state == self.vboxConstants.MachineState_PoweredOff: self.session.console.powerUp() #We wait for the machine to be really running before doing anything else while self.mach.state != self.vboxConstants.MachineState_Running: sleep(0.1) console = self.session.console self.mouse = console.mouse self.keyboard = console.keyboard self.display = console.display # Check if we have a v4l2 device to write to if vidDevName != None: self.device = open( vidDevName, 'w', 0 ) # Do not forget the 0 for unbuffered mode RGB(A), won't work otherwise fmt = V4L2_PIX_FMT_BGR32 width = 640 height = 480 self.format = v4l2_format() self.format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT self.format.fmt.pix.pixelformat = fmt self.format.fmt.pix.width = width self.format.fmt.pix.height = height self.format.fmt.pix.field = V4L2_FIELD_NONE self.format.fmt.pix.bytesperline = width * 4 self.format.fmt.pix.sizeimage = width * height * 4 self.format.fmt.pix.colorspace = V4L2_COLORSPACE_SRGB fcntl.ioctl(self.device, VIDIOC_S_FMT, self.format) self.vmDesktopCapture = V4l2Capture( self.device, self.format, self.display, self.vboxConstants.BitmapFormat_BGRA) self.vmDesktopCapture.daemon = True self.vmDesktopCapture.start() # Run the capturing thread
def main(argv): from vboxapi import VirtualBoxManager wrapper = VirtualBoxManager(None, None) # Get the VirtualBox manager mgr = wrapper.mgr # Get the global VirtualBox object vbox = wrapper.vbox print "Running VirtualBox version %s" % (vbox.version) # Get all constants through the Python wrapper code vboxConstants = wrapper.constants # Enumerate all defined machines for mach in vbox.machines: try: # Print some basic information print "Machine name: %s [%s]" % (mach.name, mach.id) 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(vbox) # 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 screenNum = 0 # From first screen (screenX, screenY, screenBPP) = display.getScreenResolution(screenNum) print " Display (%d): %dx%d, %d BPP" % ( screenNum, screenX, screenY, screenBPP) # We're done -- don't forget to unlock the machine! session.unlockMachine() except Exception, e: print "Errror [%s]: %s" % (mach.name, str(e)) traceback.print_exc()
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
import sys import os from time import gmtime, strftime from collections import namedtuple from workflow import Workflow parallels_available = os.popen('which prlctl').readline().rstrip() try: from vboxapi import VirtualBoxManager from vboxapi.VirtualBox_constants import VirtualBoxReflectionInfo mgr = VirtualBoxManager(None, None) vbox = mgr.vbox 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 for vm in vm_list:
def main(argv): from vboxapi import VirtualBoxManager # This is a VirtualBox COM/XPCOM API client, no data needed. wrapper = VirtualBoxManager(None, None) # Get the VirtualBox manager mgr = wrapper.mgr # Get the global VirtualBox object vbox = wrapper.vbox print "Running VirtualBox version %s" %(vbox.version) # Get all constants through the Python wrapper code vboxConstants = wrapper.constants # Enumerate all defined machines for mach in wrapper.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(vbox) # 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()
from vboxapi import VirtualBoxManager mgr = VirtualBoxManager(None, None) vbox = mgr.vbox name = "sys_1375885753" mach = vbox.findMachine(name) session = mgr.mgr.getSessionObject(vbox) progress = mach.launchVMProcess(session, "gui", "") progress.waitForCompletion(-1) mgr.closeMachineSession(session) #
def main(argv): from vboxapi import VirtualBoxManager # This is a VirtualBox COM/XPCOM API client, no data needed. wrapper = VirtualBoxManager(None, None) # Get the VirtualBox manager mgr = wrapper.mgr # Get the global VirtualBox object vbox = wrapper.vbox print "Running VirtualBox version %s" % (vbox.version) # Get all constants through the Python wrapper code vboxConstants = wrapper.constants # Enumerate all defined machines for mach in wrapper.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(vbox) # 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): 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
''' VirtualBox ''' import uuid import time from fish import ProgressFish from vboxapi import VirtualBoxManager fish = ProgressFish(total=100) manager = VirtualBoxManager(None, None) vbox = manager.vbox def createMachine(name, uuid=None, settings_file=None, groups=[], os_type_id='Debian', flags='', force_overwrite=False): ''' Create virtual machine Version 4.1.18: :param settingsFile: Fully qualified path where the settings file should be created, or NULL for a default folder and file based on the name argument. :param name: Machine name. :param osTypeId: Guest OS Type ID. :param id: Machine UUID (optional). :param forceOverwrite: If true, an existing machine settings file will be overwritten. :returns: IProgress
'type': myManager.type, '_machlist': None, } connect(ctx, ["http://localhost:18083/", USERNAME, PASSWORD]) oMachine = machineByName(ctx, "prethesis") if startVm(ctx, oMachine, "gui", f, sha): disconnect(ctx, ("h2sandbox", )) return True else: disconnect(ctx, ("h2sandbox", )) return False if __name__ == "__main__": # Testing the functionality of the module print "Hello World" style = "WEBSERVICE" myManager = VirtualBoxManager(style, None) ctx = { 'global': myManager, 'mgr': myManager.mgr, 'vb': None, 'const': myManager.constants, 'remote': myManager.remote, 'type': myManager.type, '_machlist': None, } connect(ctx, ["http://localhost:18083/", "test", "test"]) oMachine = machineByName(ctx, "prethesis") startVm(ctx, oMachine, "gui")
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
class VirtualBox: """A class representing a VirtualBox machine. Keyword arguments: vmname -- name of the virtual machine to be used user -- user to login as on the virtual box password -- password of the given user (default '') gui -- whenever virtualbox should show a gui (default False) silent -- whenever statusmessages should be hidden (default False) """ mgr = VirtualBoxManager(None, None) mach = None session = None guestsession = None def __init__(self, vmname, user, password='', gui=False): self.vmname = vmname logging.info("initializing VirtualBox machine: " + vmname) self.user = user self.password = password self.operation_mode = 'gui' if gui else 'headless' self.mach = self.mgr.vbox.findMachine(self.vmname) self.os = 'windows' if 'windows' in self.mach.OSTypeId.lower( ) else 'linux' # If the machine is already running, we need to stop it first if self.is_running(): self.session = self.mgr.mgr.getSessionObject(self.mgr.vbox) self.lock() self.stop() sleep(2) self.mach = self.mgr.vbox.findMachine(self.vmname) self.session = self.mgr.mgr.getSessionObject(self.mgr.vbox) def get_name_of_storage_controller(self, machine): controllers = self.mgr.getArray(machine, "storageControllers") for c in controllers: if c.bus in [storage_bus_types['IDE'], storage_bus_types['SATA']]: return c.name raise VBoxException( "no suitable IDE or SATA controller found. Please check your machine settings" ) def __get_guest_session(self): if not self.guestsession: raise VBoxException("vm is not running") return self.guestsession def __check(self): if not self.is_running(): raise VBoxException("vm is not running") def join_path(self, *argv): """Joins a path for the guest machine. Keyword arguments: *argv -- strings to be joined to a path. """ path = argv[0] sep = '\\' if self.os == 'windows' else '/' for i, arg in enumerate(argv[1:]): path += '%s%s' % (sep, arg) return path def is_running(self): """Returnes True if the guest machine is running.""" return self.mach.state == 5 def take_screenshot(self, path): """Takes a screenshot on the guest machine. Keyword arguments: path -- path on the host machine where the screenshot should be saved. """ cmd = "/usr/bin/VBoxManage controlvm " + self.vmname + " screenshotpng " + os.path.join( path, "screenshot.png") logging.info("Taking screen shot.") os.system(cmd) def machineState(self): """Returnes a string describing the machine state.""" return MACHINE_STATES[self.mach.state] def lock(self): """Locks a session on the guest machine. """ self.session = self.mgr.openMachineSession(self.mach) self.mach = self.session.machine def unlock(self): """Unlocks a session on the guest machine. Keyword arguments: session -- the session to be unlocked """ self.session.unlockMachine() def start(self, timeout=30): """Starts the viurtual machine and creates a session.""" logging.info("starting vm") self.mach = self.mgr.vbox.findMachine(self.vmname) self.session = self.mgr.getSessionObject(self.mach) progress = self.mach.launchVMProcess(self.session, self.operation_mode, "") progress.waitForCompletion(-1) # FIXME: Fails in virtualbox 4.3 with "The session is not locked (session state: Unlocked)", works in virtualbox 5.0 guest = self.session.console.guest self.guestsession = guest.createSession(self.user, self.password, "", self.user) result = self.guestsession.waitFor( self.mgr.constants.GuestSessionWaitForFlag_Start, timeout * 1000) if result == self.mgr.constants.GuestSessionWaitResult_Timeout: raise VBoxException("A session for '%s' could not be created." % self.user) def stop(self): """Stops the virtual machine guest.""" progress = self.session.console.powerDown() progress.waitForCompletion(-1) self.unlock() def reset(self): """Rolls the virtual machine back to its last snapshot.""" logging.info("resetting vm") self.lock() progress = self.mach.restoreSnapshot(self.mach.currentSnapshot) # progress = self.session.console.restoreSnapshot(self.mach.currentSnapshot) progress.waitForCompletion(-1) self.unlock() def walk(self, top): """Pseudo implentation of os.walk for the virtual guest.""" self.__check() guestSession = self.__get_guest_session() todo = [top] while todo: root = todo.pop() files = [] directories = [] directory = guestSession.directoryOpen( root, '', [self.mgr.constants.DirectoryOpenFlag_None]) while True: try: fileData = directory.read() if fileData.type == self.mgr.constants.FsObjType_File: files.append(fileData.name) elif fileData.type == self.mgr.constants.FsObjType_Directory: if fileData.name not in ['.', '..']: directories.append(fileData.name) todo.append(self.join_path(root, fileData.name)) except Exception, e: # TODO: too broad exception clause. Which exception do we want to catch here? directory.close() yield root, directories, files break
def __init__(self): ### initialize a session with virtual box self.mgr = VirtualBoxManager(None, None) self.vbox = self.mgr.vbox self.session = self.mgr.mgr.getSessionObject(self.vbox) self.package_base = "%s/%s" % (os.path.dirname(os.path.realpath(__file__)).rsplit('/',1)[0],'packages')