def test_lock_vm(self): """create a locked session for the test_vm machine""" vbox = virtualbox.VirtualBox() # Assert that we can create a lock over a machine vm = vbox.find_machine("test_vm") s = virtualbox.Session() vm.lock_machine(s, virtualbox.library.LockType.shared) self.assertTrue(s.state == virtualbox.library.SessionState.locked) # Assert we can only lock a session object once self.assertRaises( library.VBoxErrorInvalidObjectState, vm.lock_machine, s, virtualbox.library.LockType.shared, ) # Assert we can open a second session and can now apply a write lock # to the resource machine as it already has a shared lock acquired s2 = virtualbox.Session() self.assertRaises( library.VBoxErrorInvalidObjectState, vm.lock_machine, s2, virtualbox.library.LockType.write, ) # Assert that we can open a shared lock to the vm which already has # a session with a shared lock over it vm.lock_machine(s2, virtualbox.library.LockType.shared) self.assertTrue(s2.state == virtualbox.library.SessionState.locked) # Assert that unlocking the machine through s or s2 will change # the lock state of s2 back to unlocked s.unlock_machine() self.assertTrue(s.state == virtualbox.library.SessionState.unlocked) self.assertTrue(s2.state == virtualbox.library.SessionState.unlocked) # Finally, build a write lock and assert we can not open a shared lock vm.lock_machine(s, virtualbox.library.LockType.write) self.assertRaises( library.VBoxErrorInvalidObjectState, vm.lock_machine, s2, virtualbox.library.LockType.write, ) s.unlock_machine() self.assertRaises(library.VBoxError, s.unlock_machine)
def __init__(self): self.v_box = virtualbox.VirtualBox() self.v_box_constants = virtualbox.library self.vm_obj = None self.vm_session = None self.vm_snap_count = 0 self.v_box_session = virtualbox.Session()
def startvm(id): idvm = id vm = vmfind(idvm) # On recupere la vm infos = collections.OrderedDict() if vm == 0: infos['start_vm'] = 'false_vmdoesntexist' elif str(vm.state) == 'FirstOnline': #Si la vm est lancee infos['start_vm'] = 'false_vmalreadyonline' elif str(vm.state) == 'PoweredOff': #Si la vm est a l'arret if str(vm.session_state) == 'Locked': # Si la session est lock infos['start_vm'] = 'false_sessionlocked' elif str(vm.session_state ) == 'Unlocked': #Si session debloque alors on lance la vm session = virtualbox.Session() vm.launch_vm_process( session, 'headless', '') #Pas d'affiche de l'ecran lors du demarrage time.sleep(5) #Attente de cinq secondes if str(vm.state) == 'FirstOnline': #On reverifie infos['start_vm'] = 'true' else: infos['start_vm'] = 'false_startfailed' else: infos['start_vm'] = 'false_sessionunknown' else: infos['start_vm'] = 'false_statevmunknown' return infos
def initialize(cls): try: cls.vbox = virtualbox.VirtualBox() cls.vb_session = virtualbox.Session() print([x.name for x in cls.vbox.machines]) print("type intended vm name from above") cls.vm_name = input("#>") if cls.vm_name == "": cls.vm_name = "SecurityOnion" cls.vm = cls.vbox.find_machine(cls.vm_name) if cls.vm.state != 5: progress = cls.vm.launch_vm_process(cls.vb_session, "gui", []) progress.wait_for_completion() if cls.vb_session.state != 2: print( "Session state is improperly locked, something went wrong." ) else: print("logging into virtual machine") print("please enter vm root password") passwd = input("#>") # getpass.getpass() cls.vm_access = cls.vb_session.console.guest.create_session( "root", passwd) except Exception as e: print(e)
def activateWinRM(vmname): sleeptime = 60 if 'Win7' in vmname: sleeptime = 30 print 'activateWinRM: ' + vmname session = virtualbox.Session() vm = vbox.find_machine(vmname) print 'vm: ' + str(vm) progress = vm.launch_vm_process(session, 'gui', '') progress.wait_for_completion(-1) print 'Starting VM...' time.sleep(sleeptime) gs = session.console.guest.create_session('IEUser', 'Passw0rd!') print 'Creating bin directory...' gs.execute('C:\\Windows\\System32\\cmd.exe', ['/C', 'mkdir C:\\Users\\IEUser\\bin']) gs.copy_to('./bin/elevate.exe', 'C:\\Users\\IEUser\\bin\\elevate.exe') gs.copy_to('./bin/install-winrm.cmd', 'C:\\Users\\IEUser\\bin\\install-winrm.cmd') gs.copy_to('./bin/fixnetwork.ps1', 'C:\\Users\\IEUser\\bin\\fixnetwork.ps1') print 'Installing WinRM...Please click ok on the UAC prompt...' process, stdout, stderr = gs.execute( 'C:\\Users\\IEUser\\bin\\elevate.exe', ['/k', 'C:\\Users\\IEUser\\bin\\install-winrm.cmd']) print 'Sleeping 60 seconds...' time.sleep(sleeptime) print 'Removing bin directory...' process, stdout, stderr = gs.execute( 'C:\\Windows\\system32\\cmd.exe', ['/C', 'rmdir /s /q C:\\Users\\IEUser\\bin']) print 'Shutting down vm...' session.console.power_button() time.sleep(5) session.unlock_machine()
def start(): name = str(request.args.get('name')) session = virtualbox.Session() progress = getVM(name).launch_vm_process(session, "gui", []) progress.wait_for_completion(-1) sessions.append([name, session]) return redirect('/')
def __init__(self, vbox, vm_name): self.vbox = vbox self.vm_name = vm_name self.client_name = '' self.session = virtualbox.Session() self.client_ready = False self.launch_time = datetime.now() self.vm = self.vbox.find_machine(self.vm_name) self.vm.launch_vm_process(self.session, 'gui', '')
def __init__(self): self.vbox = virtualbox.VirtualBox() self.session = virtualbox.Session() try: self.machine = self.vbox.find_machine(MACHINE_NAME) self.launch() except VBoxErrorObjectNotFound: logger.error('Could not locate VM %s', MACHINE_NAME) self.machine = None
def test_power_up_down_vm(self): """power up than down the test_vm via launch""" vbox = virtualbox.VirtualBox() vm = vbox.find_machine('test_vm') s = virtualbox.Session() p = vm.launch_vm_process(s, "headless", "") p.wait_for_completion(5000) s.console.power_down() s.unlock_machine()
def install(name, **kwargs): machine = by_name(name)[0] session = virtualbox.Session() progress = machine.launch_vm_process(session) progress.wait_for_completion() console = session.console # we assume the live system on the disk has been booted after 10 seconds... time.sleep(10) console.keyboard.put_keys(['\n', 'F6', 'ESC']+['BKSP']*10+\ [x for x in 'ks=http://10.0.2.2:8000/static/xenial.ks']+['\n'])
def start_vm(name): vbox = virtualbox.VirtualBox() session = virtualbox.Session() machine = vbox.find_machine(name) if machine is not None: progress = machine.launch_vm_process(session, "headless", "") while progress.percent < 100 or not progress.completed: logging.debug(" Starting vm: " + str(progress.percent)) sleep(1) logging.debug("Machine " + machine.name + " started")
def setting(): name = str(request.args.get('name')) memory = str(request.args.get('memory')) cpu = str(request.args.get('cpu')) session = virtualbox.Session() getVM(name).lock_machine(session, library.LockType.shared) vm = session.machine vm.memory_size = int(memory) vm.cpu_count = int(cpu) vm.save_settings() session.unlock_machine() return redirect('/')
def reset(self): print("Reset") snapshot_name = "Initial" self.current_step = 0 if self.vm is not None: self.vm.session.console.power_down().wait_for_completion(-1) sleep(1) """ machine_name = None while machine_name is None: print("Available:", available_machines) if len(available_machines) > 0: machine_name = available_machines[0] else: sleep(1) """ machine_name = self.machine_name print("Starting", machine_name) import traceback import sys traceback.print_stack(file=sys.stdout) # Load VM virtual_machine = virtual_box.find_machine(machine_name) session = vb.Session() # Restore snapshot snapshot = virtual_machine.find_snapshot(snapshot_name) virtual_machine.lock_machine(session, vb.library.LockType(1)) session.machine.restore_snapshot(snapshot).wait_for_completion(-1) session.unlock_machine() # Start VM progress = virtual_machine.launch_vm_process(session, "gui") progress.wait_for_completion(-1) sleep(40) # Get screen resolution self.screen_height, self.screen_width, _, _, _, _ = session.console.display.get_screen_resolution( 0) self.vm = VirtualBoxVariables(session=session, virtual_machine=virtual_machine, snapshot=snapshot, machine_name=machine_name) return self._get_screenshot()
def terminal(): name = str(request.args.get('name')) session = virtualbox.Session() getVM(name).lock_machine(session, library.LockType.shared) retriveIpAddress(name, session) t1 = threading.Thread(target=runSsh, args=(session,)) t1.start() # session = getSession(name) # t2 = threading.Thread(target=retriveIpAddress, args=(name, session,)) # t2.start() ip = getIpAddress(name) print('gathered ip: ', str(ip)) terminal_address = 'http://' + str(ip) + ':8888/?hostname=ubuntu1-VirtualBox&username=ubuntu1&password=MTIzNA==' session.unlock_machine() return terminal_address
def reboot(self): self.stop() # wait until session status is OFF # restart again while True: gevent.sleep(1) print('machine state', self.vm.state) print('session state', self.session.state) if self.vm.state == 1 and self.session.state == 1: self.session = virtualbox.Session() self.vm = self.vbox.find_machine(self.vm_name) self.vm.launch_vm_process(self.session, 'gui', '') break self.launch_time = datetime.now()
def __init__(self, name, snapshot, username, password, sample, launch_type='headless', wait_time=30, extraction_zip='extraction', sample_name='a'): self.virtualbox = virtualbox.VirtualBox() self.session = virtualbox.Session() self.name = name self.username = username self.password = password self.sample_path = os.path.normpath( os.path.join(PROJECT_DIR, sample ) if not os.path.isabs(sample) else sample) self.sample_name = sample_name + '.exe' self.launch_type = launch_type self.wait_time = wait_time self.extraction_fn = extraction_zip + '.zip' self.deploy_location = 'C:\\maltest' self.guest_session = None self.console_session = None try: self.vm = self.virtualbox.find_machine(self.name) except virtualbox.library.VBoxErrorObjectNotFound: raise VBoxLibException( 'Couldn\'t find [%s] VM in your VirtualBox environment' % (self.name, )) try: self.snapshot = self.vm.find_snapshot(snapshot or '') except virtualbox.library.VBoxErrorObjectNotFound as e: raise VBoxLibException( 'VM has no snapshots or snapshot name is invalid!\nERROR: %s' % (str(e), )) if not os.path.isfile(self.sample_path): raise VBoxLibException('Sample [%s] can\'t be found!' % (self.sample_path, )) self.vm.create_session(session=self.session) self.session.unlock_machine()
def vm_ubuntu_execute_script(vmname=VM_ID, vmachine_username=VM_USERNAME, vmachine_pwd=VM_PWD, time_delay=30, script_path='/usr/loca/bin/xds'): try: vbox = virtualbox.VirtualBox() except ModuleNotFoundError: print('Please install virtualbox with guest ubuntu and virtualbox SDK first before using this server.') print('Download virtualbox python SDK from:') print('https://www.virtualbox.org/wiki/Downloads') session = virtualbox.Session() machine = vbox.find_machine(vmname) progress = machine.launch_vm_process(session, 'headless', '') time.sleep(time_delay) gs = session.console.guest.create_session(vmachine_username, vmachine_pwd) process, stdout, stderr = gs.execute(script_path) print(stdout)
def remove(): name = str(request.args.get('name')) vm = getVM(name) if vm.state >= library.MachineState.running: session = virtualbox.Session() vm.lock_machine(session, library.LockType.shared) try: progress = session.console.power_down() progress.wait_for_completion(-1) except Exception: print("Error powering off machine", file=sys.stderr) session.unlock_machine() time.sleep(0.5) # TODO figure out how to ensure session is really unlocked... option = library.CleanupMode.full media = vm.unregister(option) progress = vm.delete_config(media) progress.wait_for_completion(-1) media = [] return redirect('/')
def power_on(self): LOG.debug('Power on called for vm %(vm)s', {'vm': self.vm_name}) try: vm = self.vbox.find_machine(self.vm_name) if vm.state == vmstate.running: LOG.info("VM %(vm)s is already running.", {'vm': self.vm_name }) else: with virtualbox.Session() as session: progress = vm.launch_vm_process(session, 'headless', []) while session.state._value != session.state.locked._value: LOG.info("Waiting for session to reach LOCKED state. Sleeping for 2s") time.sleep(2) except virtualbox.library.OleErrorUnexpected as e: LOG.warn(e) except Exception as e: LOG.error('Error powering on the vm %(vm)s. ' 'Error: %(error)s', {'vm': self.vm_name, 'error': e}) # Command failed, but let client to retry return IPMI_COMMAND_NODE_BUSY
def remove(self, delete=True): """Unregister and optionally delete associated config Options: delete - remove all elements of this VM from the system Return the IMedia from unregistered VM """ if self.state >= library.MachineState.running: session = virtualbox.Session() self.lock_machine(session, library.LockType.shared) try: progress = session.console.power_down() progress.wait_for_completion(-1) except Exception as exc: print("Error powering off machine %s" % progress, file=sys.stderr) pass session.unlock_machine() time.sleep(0.5) # TODO figure out how to ensure session is # really unlocked... settings_dir = os.path.dirname(self.settings_file_path) if delete: option = library.CleanupMode.detach_all_return_hard_disks_only else: option = library.CleanupMode.detach_all_return_none media = self.unregister(option) if delete: progress = self.delete_config(media) progress.wait_for_completion(-1) media = [] # if delete - At some point in time virtualbox didn't do a full cleanup # of this dir. Let's double check it has been cleaned up. if delete and os.path.exists(settings_dir): shutil.rmtree(settings_dir) return media
def start_vm_process(vmname=VM_ID, vmachine_pwd=VM_PWD, time_delay=VM_DELAY1, mode='headless'): """mode can be either gui or headless.""" try: vbox = virtualbox.VirtualBox() except ModuleNotFoundError: print('Please install virtualbox with guest ubuntu and virtualbox SDK first before using this server.') print('Download virtualbox python SDK from:') print('https://www.virtualbox.org/wiki/Downloads') session = virtualbox.Session() machine = vbox.find_machine(vmname) progress = machine.launch_vm_process(session, mode, '') progress.wait_for_completion() """wait for certain sec to ensure a normal vm startup""" time.sleep(time_delay) """assume vm is password protected""" session.console.keyboard.put_keys(vmachine_pwd) session.console.keyboard.put_keys(['ENTER']) print('password delivered!') return session
def _startthevm(self): try: self.session = virtualbox.Session() self.vm = vbox.find_machine(self.jsonkey["Machine"]) if self.vm.session_state == virtualbox.library.SessionState.locked: import time print( "Machine {} seems to be already in use. Retry to check it out in 10 s" .format(self.jsonkey["Machine"])) time.sleep( 10.0 ) #We wait 10 s to give a grace time. This can happen as a race condition if the closing of the machine (for the former request) is not finished when we start this request if self.vm.session_state == virtualbox.library.SessionState.locked: raise MachineAlreadyInUse if self.jsonkey["Snapshot"] != "Current State": self.vm.lock_machine(self.session, virtualbox.library.LockType.write) snap = self.session.machine.find_snapshot( self.jsonkey["Snapshot"]) print("Checking out snapshot {}".format(snap.name)) snapshotcheckoutprogress = self.session.machine.restore_snapshot( snap) timeout = snapshotcheckoutprogress.wait_for_completion(60000) self.session.unlock_machine() if timeout: raise ProblemCheckingOutSnapshot self.progress = self.vm.launch_vm_process(self.session, 'gui', '') timeout = self.progress.wait_for_completion(30000) if timeout: print("Timeout while starting machine") raise ProblemOpenningSession pass except Exception as e: self._handleExceptions(e)
class VirtualBoxOperate: __vbox = virtualbox.VirtualBox() __session = virtualbox.Session() # __console __progress = None def __init__(self, name__or__id: str, snapshot_name_or_id: str): self.__name = name__or__id self.__snapshot = snapshot_name_or_id # name__or__idと一致するVMがあることを確認 def checkNameId(self) -> bool: try: self.__vm = self.__vbox.find_machine(self.__name) return True except: print('\"{}\" is None.'.format(self.__name)) return False #VM起動 def startVM(self): self.__progress = self.__vm.launch_vm_process(self.__session, 'gui', '') self.__console = self.__vm.create_session() time.sleep(20) #入力した文字をVMに入力(EOFが来たら終了) def inputKeyboard(self): # print() # input_key='' while (True): try: input_key = input('Input or EOF>:') # print(input_key) # Nがnに変換される(なぞ)、日本語は遅れない self.__session.console.keyboard.put_keys(input_key + '\n') except EOFError: break #キー情報を送る(未完) def inputKey(self): while (True): try: print('press:') press_key = ord(getch()) print('hold :') hold_key = ord(getch()) self.__session.console.keyboard.put_keys(press_keys=hex(91), hold_keys=None) except EOFError: break # ログイン(Win ver)(未テスト) def loginWindows(self): username = input('username>:') passwd = input('password>:') with self.__vm.create_session() as session: with session.console.guest.create_session(user=username, password=passwd) as gs: print(gs.directory_exists("C:\\Windows")) #スナップショットの確認 def checkSnapshot(self) -> bool: try: self.__vmsnap = self.__vm.find_snapshot(self.__snapshot) return True except: print('\"{}\" is None.'.format(self.__snapshot)) return False #VM終了 def endVM(self): self.__session.console.power_down() time.sleep(10) if self.checkSnapshot(): self.__vm.restore_snapshot(self.__vmsnap) def test(self): # while (True): # try: # a = input('num:') # a = int(a) # self.__session.console.keyboard.put_keys(press_keys=['LWIN'], hold_keys=None) # except EOFError: # break input('test:') gs = self.__vm.create_session().console.guest.create_session( user='******', password='******') print(gs) print(self.__session.state) gs.execute(command="C:\\Windows\\System32\\cmd.exe")
def create_v_box_session(self): """ :return: """ self.v_box_session = virtualbox.Session()
def set_vm(self, vm_name_string="", vm_disk_path_string="", vm_manager_value=VIRTUALBOX, vm_timeout_value=360): if (not vm_name_string) and (not vm_disk_path_string): self.logfile.write( "Unable to initialize without the virtual machine name and/or the disk path.\n" ) raise ValueError( "Unable to initialize without the virtual machine name and/or the disk path.\n" ) self.logfile.write( "Attempting to initialize virtual machine by virtual machine name and path.\n" ) self.vm_disk_path = vm_disk_path_string self.vm_manager = vm_manager_value self.vm_timeout = vm_timeout_value if not self.check_if_vm_manager_implemented(): self.logfile.write( "\tVirtual Machine manger specified currently unimplemented.\n" ) raise ValueError( "\tThe virtual machine mananager specified is not currently " "supported {}.\n".format(self.vm_manager)) if self.vm_manager == VMManage.VIRTUALBOX: self.vm_wrapper = virtualbox.VirtualBox() self.vm_session = virtualbox.Session() if vm_name_string: self.vm_name = vm_name_string self.vm_instance = self.vm_wrapper.find_machine(self.vm_name) if not self.vm_instance: self.logfile.write( "\tFailed to find virtual machine {}\n".format( self.vm_name)) raise ValueError( "\tFailed to find virtual machine {}\n".format( self.vm_name)) if vm_disk_path_string: self.vm_disk_path = vm_disk_path_string self.configure_controller_from_name_and_path() elif not self.find_vm_disk_path_from_name(): self.logfile.write( "\tFailed to find virtual disk associated with virtual machine " "{}\n".format(self.vm_name)) raise virtualbox.library.VBoxErrorVmError( "\tNo storage media found attached to virtual machine") else: if not self.find_vm_name_from_path(): self.logfile.write( "Failed to find virtual machine with drive path {}\n". format(self.vm_disk_path)) return False else: self.vm_instance = self.vm_wrapper.find_machine(self.vm_name) if self.vm_wrapper and self.vm_instance: self.logfile.write( "\tSuccessfully initialized virtual machine by name and path.\n" ) return True else: self.logfile.write( "\tFailed to successfully initialize virtual machine by name and path.\n" ) return False
def start(self): logging.info("Starting the VM") session = virtualbox.Session() power_up_process = self.vm.launch_vm_process(session, 'gui', '') power_up_process.wait_for_completion() session.unlock_machine()
def __init__(self, mode, adb_port, ssh_port): self.vm = virtualbox.VirtualBox().find_machine(self.machine_name) self.session = virtualbox.Session() self.mode = mode self.adb_port = adb_port self.ssh_port = ssh_port
def stop(): name = str(request.args.get('name')) session = virtualbox.Session() getVM(name).lock_machine(session, library.LockType.shared) session.console.power_down() return redirect('/')
import virtualbox import time import sys vbox = virtualbox.VirtualBox() session = virtualbox.Session() machine = vbox.find_machine("IE8 - Win7") machine.lock_machine(session, virtualbox.library.LockType.shared) console = session.console guest = console.guest guestSesssion = guest.create_session("IEUser", "Passw0rd!", "", "s1") igp = guestSesssion.process_create( "C:\\Users\\IEUser\\AppData\\Local\\Programs\\Python\\Python37-32\\python.exe", ["C:\\Users\\IEUser\\echo.py"], [], [], 20000) while True: if igp.status == virtualbox.library.ProcessStatus.started: break print("Wait for started but %s" % igp.status) time.sleep(1) #print("Wait for started") #igp.waitForOperationCompletion(1, 10000) # waitFor(virtualbox.library.ProcessWaitForFlag.start, 10000) # print("Wait for stdin ready") # igp.waitFor(virtualbox.library.ProcessWaitForFlag.std_in, 10000) while True: print("Enter line:")
def launch_machine(vm_name): session = virtualbox.Session() machine = vbox.find_machine(vm_name) progress = machine.launch_vm_process(session, "gui", []) progress.wait_for_completion()