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 _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 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')
예제 #4
0
파일: wvbox.py 프로젝트: wajika/H2Sandbox
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
예제 #5
0
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
예제 #6
0
파일: vbox.py 프로젝트: cfoch/vbox-importer
    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
예제 #7
0
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)
예제 #8
0
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)
예제 #9
0
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
예제 #10
0
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)
예제 #11
0
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)
예제 #12
0
 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
예제 #13
0
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()
예제 #14
0
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")
예제 #15
0
	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
예제 #16
0
    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
예제 #17
0
    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
예제 #18
0
    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
예제 #19
0
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()
예제 #20
0
    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
예제 #21
0
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
예제 #22
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()
예제 #23
0
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) ?")
예제 #24
0
파일: wvbox.py 프로젝트: wajika/H2Sandbox
        '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")
예제 #25
0
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
예제 #26
0
 def __init__(self):
     self.mgr = VirtualBoxManager(None, None)
     self.vbox = self.mgr.vbox
예제 #27
0
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
예제 #28
0
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
예제 #29
0
IP = ""
VBOX_INSTANCES = {}
FORCE_IPV6 = False
VBOX_STREAM = 0
VBOXVER = 0.0
VBOXVER_REQUIRED = 4.1
CACHED_REPLY = ""
CACHED_REQUEST = ""
CACHED_TIME = 0.0
g_stats=""
g_vboxManager = 0
g_result=""

try:
    from vboxapi import VirtualBoxManager
    g_vboxManager = VirtualBoxManager(None, None)
except:
    pass

#Working Dir in VirtualBox is mainly needed for "Traffic Captures".
WORKDIR = os.getcwdu()
if os.environ.has_key("TEMP"):
    WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace')
elif os.environ.has_key("TMP"):
    WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace')

class UDPConnection:
    def __init__(self, sport, daddr, dport):
        debugmsg(3, "class UDPConnection::__init__(%s, %s, %s)" % (str(sport), str(daddr), str(dport)))
        self.sport = sport
        self.daddr = daddr
예제 #30
0
class CardapioPlugin(CardapioPluginInterface):

    author = 'Clifton Mulkey'
    name = _('VirtualBox')
    description = _(
        'Search for and start VirtualBox virtual machines from the menu')

    # not used in the GUI yet:
    url = ''
    help_text = ''
    version = '1.24'

    plugin_api_version = 1.40

    search_delay_type = None

    default_keyword = 'vbox'

    category_name = _('Virtual Machines')
    category_icon = 'VBox'
    icon = 'VBox'
    category_tooltip = _('Your VirtualBox virtual machines')

    hide_from_sidebar = False

    # Set to "False" to show the "Virtual Machines" category all the time
    # Set to "True" to only show it when searching

    def __init__(self, cardapio_proxy, category):
        '''	
		This method is called when the plugin is enabled.
		Here the variables are initialized an the list of virtual machines is built.
		'''

        self.c = cardapio_proxy

        try:
            import os
            import gio
            from vboxapi import VirtualBoxManager

        except Exception, exception:
            self.c.write_to_log(self,
                                "Error importing some modules: %s" % exception,
                                is_error=True)
            self.loaded = False
            return

        self.os = os
        self.gio = gio

        try:
            subprocess.Popen(['VBoxManage'], stdout=subprocess.PIPE)

        except OSError:
            self.c.write_to_log(
                self,
                "VBoxManage command not recognized: Maybe virtualbox is not installed...",
                is_error=True)
            self.loaded = False
            return

        self.vboxmgr = VirtualBoxManager(None, None)
        self.load_vm_items()

        machine_path = self.vboxmgr.vbox.systemProperties.defaultMachineFolder

        if self.os.path.exists(machine_path):
            self.package_monitor = self.gio.File(
                machine_path).monitor_directory()
            self.package_monitor.connect('changed', self.on_vms_changed)

        else:
            self.c.write_to_log(self,
                                'Path does not exist:' + machine_path,
                                is_warning=True)
            self.c.write_to_log(
                self,
                'Will not be able to monitor for virtual machine changes',
                is_warning=True)

        self.loaded = True