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())
예제 #2
0
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
예제 #3
0
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()
예제 #4
0
파일: clienttest.py 프로젝트: mcenirm/vbox
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()
예제 #5
0
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