예제 #1
0
def test_task(uuid, box):
    ret = False
    try:
        folder = path.join(box["temp"], uuid)
        virtual_machine = VirtualBox().find_machine(box["vm"])
        with virtual_machine.create_session() as session:
            session.unlock_machine()
            proc = virtual_machine.launch_vm_process(session, "gui", "")
            proc.wait_for_completion(timeout=-1)
            with session.console.guest.create_session(box["user"],
                                                      box["pass"]) as gs:
                if box["os"] == "Linux":
                    gs.environment_schedule_set("DISPLAY", ":0")
                    process, stdout, stderr = gs.execute("bin/ls")
                    if len(stdout) > 0:
                        ret = True
                elif box["os"] == "Windows":
                    process, stdout, stderr = gs.execute(
                        "%WINDIR%\\system32\\cmd.exe", ["/C", "dir"])
                    if len(stdout) > 0:
                        ret = True
            session.console.power_down()
    except Exception as e:
        log_string(uuid, "custom_task Failed {}".format(e), "Red")
    return ret
예제 #2
0
def custom_task(uuid, box, actions_list):
    ret = False
    try:
        folder = path.join(box["temp"], uuid)
        file_recording(uuid, box["vm"],
                       path.join(folder, box["screen_recorder"]))
        virtual_machine = VirtualBox().find_machine(box["vm"])
        with virtual_machine.create_session() as session:
            session.unlock_machine()
            file_recording(uuid, box["vm"],
                           path.join(folder, box["screen_recorder"]))
            proc = virtual_machine.launch_vm_process(session, "headless", "")
            proc.wait_for_completion(timeout=-1)
            #do not timeout the session.console.guest.create_session timeout_ms=5*1000 (some vms)
            with session.console.guest.create_session(box["user"],
                                                      box["pass"]) as gs:
                #fix issues with display
                if box["os"] == "Linux":
                    gs.environment_schedule_set("DISPLAY", ":0")
                sleep(1)
                session.machine.recording_settings.enabled = True
                sleep(1)
                parse_actions(uuid, box, folder, session, gs, actions_list)
                sleep(1)
                session.machine.recording_settings.enabled = False
                take_screenshot(uuid, box["vm"],
                                path.join(folder, box["screenshot"]))
                sleep(1)
                ret = True
            session.console.power_down()
    except Exception as e:
        log_string(uuid, "custom_task Failed {}".format(e), "Red")
    return ret
예제 #3
0
def turn_off(uuid, box, timeout):
    ret = False
    try:
        log_string(
            uuid, "{} Status {}".format(box["vm"],
                                        show_status(uuid, box["vm"])),
            "Yellow")
        timeout_start = time()
        virtual_machine = VirtualBox().find_machine(box["vm"])
        if Session().state == SessionState(2):
            Session().unlock_machine()
        if virtual_machine.state != MachineState.aborted:
            with virtual_machine.create_session() as session:
                if virtual_machine.state == MachineState.saved:
                    session.machine.discard_saved_state(True)
                elif virtual_machine.state != MachineState.powered_off:
                    session.console.power_down()
                    while virtual_machine.state != MachineState.powered_off and (
                            time() < timeout_start + timeout):
                        log_string(uuid, "Waiting on {}".format(box["vm"]),
                                   "Yellow")
                        sleep(2)
            if virtual_machine.state == MachineState.powered_off:
                log_string(uuid, "VM is powered off {}".format(box["vm"]),
                           "Yellow")
        ret = True
    except Exception as e:
        log_string(uuid, "turn_off Failed {}".format(e), "Red")
    return ret
예제 #4
0
    def init(self):
        with open("run.json", "r") as file:
            run = json.load(file)
            for commands in run:
                vbox = VirtualBox()
                session = Session()
                vm = vbox.find_machine(VBOX_MACHINE_NAME)
                p = vm.launch_vm_process(session, 'gui', '')
                p.wait_for_completion(60 * 1000)
                session = vm.create_session()
                gs = session.console.guest.create_session(VBOX_USER_NAME,
                                                          VBOX_PASSWORD,
                                                          timeout_ms=300 *
                                                          1000)
                for command in commands:
                    print("Command: %s" % (command['command']))
                    print("Parameters: %s" % (command['parameters']))
                    print("Sleep: %s" % (command['sleep']))
                    try:
                        process, stdout, stderr = gs.execute(
                            command['command'],
                            command['parameters'],
                            timeout_ms=30 * 1000)
                        print(stdout)
                        time.sleep(int(command['sleep']))
                    except:
                        pass

                self._power_down(session)
                self._extract_victims(
                    VICTIMS_FOLDER_IN,
                    datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
                self._delete_victims(VICTIMS_FOLDER_IN)
예제 #5
0
def delete_machine(uuid, box):
    try:
        virtual_machine = VirtualBox().find_machine(box["vm"])
        virtual_machine.remove(delete=True)
        log_string(uuid, "{} was deleted".format(box["vm"]), "Red")
        return True
    except Exception as e:
        log_string(uuid, "delete_machine Failed {}".format(e), "Red")
        return False
예제 #6
0
파일: pool.py 프로젝트: dwattttt/pyvbox
 def _power_down(self, session):
     vbox = VirtualBox()
     clone = vbox.find_machine(session.machine.name)
     try:
         p = session.console.power_down()
         p.wait_for_completion(60*1000)
         session.unlock_machine()
         session = clone.create_session()
         console = session.console
         p = console.restore_snapshot()
         p.wait_for_completion(60*1000)
         return clone
     finally:
         if session.state == SessionState.locked:
             session.unlock_machine()
예제 #7
0
파일: pool.py 프로젝트: maxfragg/pyvbox
 def _power_down(self, session):
     vbox = VirtualBox()
     clone = vbox.find_machine(session.machine.name)
     try:
         p = session.console.power_down()
         p.wait_for_completion(60 * 1000)
         session.unlock_machine()
         session = clone.create_session()
         console = session.console
         p = console.restore_snapshot()
         p.wait_for_completion(60 * 1000)
         return clone
     finally:
         if session.state == SessionState.locked:
             session.unlock_machine()
예제 #8
0
def get_machines(base_name):
    v_box = VirtualBox()
    all_machines = v_box.machines
    machines = []
    for machine in all_machines:
        if base_name in machine.name:
            machines.append(machine)
    return machines
예제 #9
0
 def _new_instance(cls, docker_manager):
     try:
         from virtualbox import VirtualBox
         from virtualbox.library import ISession, LockType
     except ImportError:
         return None
     return VirtualBoxHypervisor(docker_manager, VirtualBox(), ISession,
                                 LockType)
예제 #10
0
def get_machine_status(uuid, box):
    try:
        virtual_machine = VirtualBox().find_machine(box["vm"])
        log_string(uuid, "machine status is {}".format(virtual_machine.state),
                   "Red")
        return True
    except:
        log_string(uuid, "get_machine_status Failed {}".format(e), "Red")
        return False
예제 #11
0
def create_dummy_machine(uuid, box):
    try:
        log_string(uuid, "Creating {}".format(box["vm"]), "Green")
        machine = VirtualBox().create_machine(settings_file="",
                                              name=box["vm"],
                                              os_type_id="",
                                              groups=['/'],
                                              flags="")
        VirtualBox().register_machine(machine)
        virtual_machine = VirtualBox().find_machine(box["vm"])
        with virtual_machine.create_session() as session:
            process, x = session.machine.take_snapshot(
                box["snapshot"],
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), True)
            process.wait_for_completion(timeout=-1)
            return True
    except Exception as e:
        log_string(uuid, "create_dummy_machine Failed {}".format(e), "Red")
예제 #12
0
파일: pool.py 프로젝트: mjdorma/pyvbox
 def _power_down(self, session):
     vbox = VirtualBox()
     clone = vbox.find_machine(session.machine.name)
     try:
         p = session.console.power_down()
         p.wait_for_completion(60 * 1000)
         try:
             session.unlock_machine()
         except OleErrorUnexpected:
             # session seems to become unlocked automatically after
             # wait_for_completion is called after the power_down?
             pass
         session = clone.create_session()
         p = session.machine.restore_snapshot()
         p.wait_for_completion(60 * 1000)
         return clone
     finally:
         if session.state == SessionState.locked:
             session.unlock_machine()
예제 #13
0
def check_if_exists_machines(uuid, box):
    try:
        for machine in VirtualBox().machines:
            if box["vm"] == machine.name:
                log_string(uuid, "{} exists".format(box["vm"]), "Green")
                return True
        log_string(uuid, "{} does not exist".format(box["vm"]), "Green")
        return False
    except Exception as e:
        log_string(uuid, "check_if_exists_machines Failed {}".format(e), "Red")
예제 #14
0
 def _power_down(self, session):
     vbox = VirtualBox()
     clone = vbox.find_machine(session.machine.name)
     try:
         p = session.console.power_down()
         p.wait_for_completion(60 * 1000)
         try:
             session.unlock_machine()
         except OleErrorUnexpected:
             # session seems to become unlocked automatically after
             # wait_for_completion is called after the power_down?
             pass
         session = clone.create_session()
         p = session.machine.restore_snapshot()
         p.wait_for_completion(60 * 1000)
         return clone
     finally:
         if session.state == SessionState.locked:
             session.unlock_machine()
예제 #15
0
파일: pool.py 프로젝트: maxfragg/pyvbox
 def _clones(self):
     "Yield all machines under this pool"
     vbox = VirtualBox()
     machines = []
     for machine in vbox.machines:
         if machine.name == self.machine_name:
             continue
         if machine.name.startswith(self.machine_name):
             machines.append(machine)
     return machines
예제 #16
0
파일: pool.py 프로젝트: dwattttt/pyvbox
 def _lock(self, timeout_ms=-1):
     "Exclusive lock over root machine"
     vbox = VirtualBox()
     machine = vbox.find_machine(self.machine_name)
     wait_time = 0
     while True:
         session = Session()
         try:
             machine.lock_machine(session, LockType.write)
         except Exception as exc:
             if timeout_ms != -1 and wait_time > timeout_ms:
                 raise ValueError("Failed to acquire lock - %s" % exc)
             time.sleep(1)
             wait_time += 1000
         else:
             try:
                 yield session
             finally: 
                 session.unlock_machine()
             break
예제 #17
0
파일: pool.py 프로젝트: maxfragg/pyvbox
 def _lock(self, timeout_ms=-1):
     "Exclusive lock over root machine"
     vbox = VirtualBox()
     machine = vbox.find_machine(self.machine_name)
     wait_time = 0
     while True:
         session = Session()
         try:
             machine.lock_machine(session, LockType.write)
         except Exception as exc:
             if timeout_ms != -1 and wait_time > timeout_ms:
                 raise ValueError("Failed to acquire lock - %s" % exc)
             time.sleep(1)
             wait_time += 1000
         else:
             try:
                 yield session
             finally:
                 session.unlock_machine()
             break
예제 #18
0
def restore_machine(uuid, box):
    restoring_machine = False
    ret = False
    try:
        virtual_machine = VirtualBox().find_machine(box["vm"])
        snap = virtual_machine.find_snapshot(box["snapshot"])
        with virtual_machine.create_session() as session:
            try:
                restoring = session.machine.restore_snapshot(snap)
                restoring.wait_for_completion(-1)
                if restoring.completed == 1:
                    log_string(uuid,
                               "Restoring completed {}".format(box["vm"]),
                               "Green")
                    restoring_machine = True
            except Exception as e:
                log_string(uuid, "start_task Failed {}".format(e), "Red")
            if restoring_machine:
                ret = True
    except Exception as e:
        log_string(uuid, "start_task Failed {}".format(e), "Red")
    return ret
예제 #19
0
    def _new_instance(cls,
                      get_config_fn: GetConfigFunction,
                      docker_vm: str = DOCKER_VM_NAME) -> Hypervisor:

        init_pythoncom()

        try:
            from virtualbox import VirtualBox
            from virtualbox.library import ISession, LockType
        except ImportError as err:
            logger.error('Error importing VirtualBox libraries: %r', err)
            raise

        return VirtualBoxHypervisor(get_config_fn, VirtualBox(), ISession,
                                    LockType, docker_vm)
예제 #20
0
    def vms(self):
        vbox = VirtualBox()
        running_vms = len(
            list(
                filter(lambda m: m.state != MachineState.powered_off,
                       vbox.machines)))
        full_text = self.py3.safe_format(self.format, {'number': running_vms})
        #print(full_text)

        if running_vms > 0:
            color = self.py3.COLOR_BAD
        else:
            color = self.py3.COLOR_GOOD

        return {
            'full_text': full_text,
            'color': color,
            'cached_until': self.py3.time_in(seconds=120)
        }
예제 #21
0
def vbox_remote_control(uuid, box):
    ret = False
    try:
        queue = Redis.from_url(redis_settings_docker)
        virtual_machine = VirtualBox().find_machine(box["vm"])
        vm_name_lock = "{}_lock".format(box["vm"])
        vm_name_frame = "{}_frame".format(box["vm"])
        vm_name_action = "{}_action".format(box["vm"])
        with virtual_machine.create_session() as session:
            session.unlock_machine()
            proc = virtual_machine.launch_vm_process(session, "headless", "")
            proc.wait_for_completion(timeout=-1)
            with session.console.guest.create_session(box["user"],
                                                      box["pass"]) as gs:
                h, w, _, _, _, _ = session.console.display.get_screen_resolution(
                    0)
                update_item(mongo_settings_docker["worker_db"],
                            mongo_settings_docker["worker_col_logs"], uuid, {
                                "status": "live",
                                "started_time": datetime.now()
                            })
                queue.set(vm_name_lock, "False")
                while queue.get(vm_name_lock) == b"False":
                    x, y, dz, dw, button_state, key = "false", "false", "false", "false", "false", "false"
                    try:
                        t = queue.get(vm_name_action)
                        if t and t != "None":
                            x, y, dz, dw, button_state, key = loads(t)
                            #log_string(uuid,">>>>>>>>>> {} {} {} {} {} {}".format(x,y,dz,dw,button_state,key),"Red")
                    except e:
                        pass
                    try:
                        if key != "false":
                            session.console.keyboard.put_scancodes(
                                list(scan_code_table[key]))
                        if "false" not in (x, y, dz, dw, button_state):
                            session.console.mouse.put_mouse_event_absolute(
                                x, y, dz, dw, 0)
                            if button_state == "leftclick":
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 1)
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 0)
                            elif button_state == "leftdoubleclick":
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 1)
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 0)
                            elif button_state == "rightclick":
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 2)
                                session.console.mouse.put_mouse_event_absolute(
                                    x, y, dz, dw, 0)
                        queue.set(vm_name_action, "None")
                        png = session.console.display.take_screen_shot_to_array(
                            0, h, w, BitmapFormat.png)
                        queue.set(vm_name_frame, png)
                    except:
                        pass
                    sleep(.2)
                ret = True
            session.console.power_down()
    except Exception as e:
        log_string(uuid, "custom_task Failed {}".format(e), "Red")
    return ret
예제 #22
0
파일: __init__.py 프로젝트: goffinet/kcli
 def __init__(self):
     try:
         self.conn = VirtualBox()
     except Exception:
         self.conn = None
예제 #23
0
def initialize():
    global vbox
    vbox = VirtualBox()
예제 #24
0
from virtualbox import Session, VirtualBox
from virtualbox.library import MachineState


import time
import sys

poll_time = 30

try:
    vbox = VirtualBox()
    session = Session()
except ModuleNotFoundError as e:
    if "vboxapi" in e.msg:
        print("Module 'vboxapi' is missing. Installation steps:")
        print("1. Download the VirtualBox SDK at https://www.virtualbox.org/wiki/Downloads")
        print("2. Extract ZIP")
        print("3. Navigate to installer directory")
        print("4. Run python vboxapisetup.py install")
        sys.exit(-1)
    else:
        raise e

# https://raw.githubusercontent.com/sethmlarson/virtualbox-python/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py

while True:
    machines = list(filter(lambda machine: machine.name.startswith("PIAV"), vbox.machines))
    print("{} VMs found".format(len(machines)))
    for machine in machines:
        print("{}'s state: {}".format(machine.name, machine.state))
        if machine.state == MachineState.powered_off:
예제 #25
0
 def __init__(self):
     try:
         self.conn = VirtualBox()
     except Exception as e:
         print(e)
         self.conn = None
예제 #26
0
def running_vagrant_boxes():
    vbox = VirtualBox()
    return [vm.name for vm in vbox.machines if vm.state == MachineState(5)]