示例#1
0
def create_vm():
    vbox: virtualbox.VirtualBox = virtualbox.VirtualBox()
    vm_names: List[str] = [machine.name for machine in vbox.machines]
    if VM_NAME in vm_names:
        if VM_IGNORE_DUPLICATES is False:
            raise BaseStageException(
                F"It seems like there's a vm that has the same name that was going to be created ({VM_NAME}).\n"
                F"Either rename the VM, set the vm_name in config.ini to something else or set ignore_duplicates to 1 in the environment variables."
            )
        print(
            f"[yellow]There's a VM with the same name ({VM_NAME}). Continuing anyway..."
        )

    try:
        vm: virtualbox.library.IMachine = vbox.create_machine(
            name=VM_NAME,
            os_type_id="ArchLinux_64",
            groups=["/"],
            flags="",
            settings_file="")
        vbox.register_machine(vm)
    except virtualbox.library_ext.library.VBoxErrorFileError:
        pass
    print("[blue]Created and registered Arch Linux VM." if "arch-linux" not in
          vm_names else "[blue]Got Arch Linux VM.")
示例#2
0
    def __init__(self):
        l.info("PerformanceMonitor module starting...")

        # Obtain the performance collector built into virtual box
        self._vbox = virtualbox.VirtualBox()
        # self._vms = self._vbox.performance_collector
        # self._vms.setup_metrics(["*"], [], 10, 15)

        # Get the file path to the location where new virtual machines
        # will be created by virtualbox
        vm_path = self._vbox.system_properties.default_machine_folder

        # Obtain physical devices
        try:
            mounts = psutil.disk_partitions(all=False)
        except UnicodeDecodeError:
            l.exception("Unable to determine the physical devices of the machine.")

        # Find which storage device contains the virtual machines
        if platform.system() == 'Windows':
            anchor = os.path.splitdrive(vm_path)[0]

            for m in mounts:
                if m.mountpoint == anchor:
                    self.mount = m.mountpoint
                    l.debug("Mount containing VMs: %s", self.mount)
                    break
        else:
            self.mount = '/'
示例#3
0
 def test_extra_data_changed(self):
     vbox = virtualbox.VirtualBox()
     vbox.register_on_extra_data_changed(self.extra_data_callback)
     # Cause a change event
     vbox.set_extra_data('test', 'data')
     vbox.set_extra_data('test', 'dataa')
     self.assertTrue(self.called)
示例#4
0
def setup(network_matrix):
    vbox = virtualbox.VirtualBox()
    all_machines = vbox.machines
    vm_names, topology_matrix = fetch_topology(network_matrix)
    vms = fetch_req_vms(vm_names, all_machines)
    networks = fetch_networks(vm_names, topology_matrix)
    return vms, networks
示例#5
0
 def __init__(self):
     self.vbox = virtualbox.VirtualBox()
     self.path = self.find_vboxmanage()
     self.list_vm = self.getAvailableVMs()
     self.currentVMID = ""
     self.username = "******"
     self.password = "******"
示例#6
0
def set_power( paramaters ):
  vm_uuid = paramaters[ 'uuid' ]
  vm_name = paramaters[ 'name' ]
  desired_state = paramaters[ 'state' ]
  logging.info( 'virtualbox: setting power state of "{0}"({1}) to "{2}"...'.format( vm_name, vm_uuid, desired_state ) )
  vbox = virtualbox.VirtualBox()

  vm = vbox.find_machine( vm_name )

  curent_state = _power_state_convert( vm.state )
  if curent_state == desired_state or ( curent_state == 'off' and desired_state == 'soft_off' ):
    return { 'state': curent_state }

  session = None
  if desired_state in ( 'off', 'soft_off' ):
    session = vm.create_session()

  progress = None
  if desired_state == 'on':
    progress = vm.launch_vm_process()
  elif desired_state == 'off':
    session.console.power_down()
  elif desired_state == 'soft_off':
    progress = session.console.power_button()

  if progress is not None:
    while not progress.completed:
      logging.debug( 'virtualbox: vm "{0}"({1}) power "{2}" at {3}%, {4} seconds left'.format( vm_name, vm_uuid, desired_state, progress.percent, progress.time_remaining ) )
      time.sleep( 1 )

  # if failed???

  logging.info( 'virtualbox: setting power state of "{0}"({1}) to "{2}" complete'.format( vm_name, vm_uuid, desired_state ) )
  return { 'state': _power_state_convert( vm.state ) }
示例#7
0
def config_ssh(vms):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        session.console.keyboard.put_keys("arcos_cli\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("config\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("system ssh-server enable true\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys(
            "system ssh-server permit-root-login true\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys(
            "system aaa authentication admin-user admin-password arrcus\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("commit\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("exit\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys(
            "show running-config system | display xml | save /var/confd/cdb/ztp.xml\n"
        )
        time.sleep(0.2)
        session.console.keyboard.put_keys("\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("exit\n")
        time.sleep(0.2)
示例#8
0
 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()
示例#9
0
    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)
示例#10
0
    def load(self, ctx):
        super(VNCBotPlugin, self).load(ctx)

        self.live = None
        self.lock = Semaphore()
        self.vbox = virtualbox.VirtualBox()
        self.vm = self.vbox.find_machine(self.config.vm_name)
        self.session = self.vm.create_session()
示例#11
0
    def __init__(self):
        self.logger = logging.getLogger()
        self.logger.info('initialising screen...')
        self.vbox = virtualbox.VirtualBox()

        self.vm = self.vbox.machines[0]
        self.vm_session = self.vm.create_session()
        self.vm_res = self.vm_session.console.display.get_screen_resolution(0)
示例#12
0
def get_metadata(machine):
    vbox = virtualbox.VirtualBox()
    vm = vbox.find_machine(machine)
    metadata = []
    types, values, timestamps, flags = vm.enumerate_guest_properties("")
    for t, v in zip(types, values):
        metadata.append(MetadataEntry(key=t, value=v))
    return metadata
示例#13
0
def create_hypervisor(hypervisor_type, *args, **kwargs):
    if hypervisor_type == HYPERVISOR_WORKSTATION:
        workstation.Workstation(*args, **kwargs)
    elif hypervisor_type == HYPERVISOR_VIRTUALBOX:
        virtualbox.VirtualBox(*args, **kwargs)
    else:
        raise NotImplementedError(
            "hypervisor {} not support".format(hypervisor_type))
示例#14
0
 def test_raises(self):
     vbox = virtualbox.VirtualBox()
     try:
         vbox.find_machine('blah blah X')
     except VBoxError as exc:
         pass
     else:
         self.fail("VBoxError not raised")
示例#15
0
 def __init__(self, image, name, arch, release):
     self.image = image
     self.name = name
     self.arch = arch
     self.release = release
     self.vbox = virtualbox.VirtualBox()
     manager = virtualbox.Manager()
     self.session = manager.get_session()
示例#16
0
def stop_vm(name):
    vbox = virtualbox.VirtualBox()
    machine = vbox.find_machine(name)
    session = machine.create_session()
    progress = session.console.power_down()
    while progress.percent < 100 or not progress.completed:
        logging.debug("Powering down: " + str(progress.percent))
        sleep(1)
示例#17
0
 def __init__(self):
     try:
         self.vbox = virtualbox.VirtualBox()
         config = ConfigObj("config.ini")
         self.control_name = config['control']
         self.control_name = 'Windows'
         self.start_vm()
     except Exception as e:
         print(e)
示例#18
0
def power_state( paramaters ):
  vm_uuid = paramaters[ 'uuid' ]
  vm_name = paramaters[ 'name' ]
  logging.info( 'virtualbox: getting "{0}"({1}) power state...'.format( vm_name, vm_uuid ) )
  vbox = virtualbox.VirtualBox()

  vm = vbox.find_machine( vm_uuid )

  return { 'state': _power_state_convert( vm.state ) }
示例#19
0
def run_commands(vms, commands):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        # session.console.keyboard.put_keys("exit\n")
        session.console.keyboard.put_keys(commands + '\n')
        time.sleep(0.2)
示例#20
0
def dhclient_mgmt_intf(vms):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        # session.console.keyboard.put_keys("exit\n")
        session.console.keyboard.put_keys("\n sudo dhclient ma1\n")
        time.sleep(0.2)
示例#21
0
 def __init__(self):
     self.vbox = virtualbox.VirtualBox()
     self.vbox_list = [vm.name for vm in self.vbox.machines]
     self.vbox_machines = []
     self.names = {'win64': 'nnnlife',
                   'win64-trader': 'hhhlife',
                   'vvvlife': 'vvvlife',
                   'wwwlife': 'wwwlife'}
     print('VBOX List', self.vbox_list)
示例#22
0
    def test_extra_data_changed(self):
        vbox = virtualbox.VirtualBox()
        vbox.register_on_extra_data_changed(self.extra_data_callback)
        # Cause a change event
        vbox.set_extra_data("test", "data")
        vbox.set_extra_data("test", "dataa")

        time.sleep(1)
        self.assertTrue(self.called)
示例#23
0
def show_ip_mgmt(vms):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        # session.console.keyboard.put_keys("exit\n")
        session.console.keyboard.put_keys("\n ip a show ma1\n")
        time.sleep(0.2)
 def setUp(self):
     self.vbox = virtualbox.VirtualBox()
     self.vm = self.vbox.find_machine('test_vm')
     self._powered_up = False
     if self.vm.state < virtualbox.library.MachineState.running:
         self._powered_up = True
         p = self.vm.launch_vm_process()
         p.wait_for_completion()
     self.session = self.vm.create_session()
示例#25
0
 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()
示例#27
0
def login(vms):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        session.console.keyboard.put_keys("\nroot\n")
        time.sleep(0.2)
        session.console.keyboard.put_keys("arrcus\n")
        time.sleep(0.2)
示例#28
0
def flush_interfaces(vms, networks):
    for vm_name in vms:
        a = str(vm_name)
        vbox = virtualbox.VirtualBox()
        machine = vbox.find_machine(a)
        session = machine.create_session()
        for i, interface in enumerate(networks[a]):
            session.console.keyboard.put_keys("\n ip a flush swp" +
                                              str(i + 1) + " \n")
        session.console.keyboard.put_keys("\n ip a flush loopback0\n")
示例#29
0
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")
示例#30
0
	def __init__(self):
		super().__init__()

		self.vbox = virtualbox.VirtualBox()
		self.config = configparser.ConfigParser()
		self.config.read("config.ini")
		self.assets = json.load(open("assets.json", "r"))
		self.previous_formatdict = None

		client_id = self.config["Rich Presence"]["client_id"]
		self.RPC = Presence(client_id)
		self.RPC.connect()
		self.start_time = time.time()
		print("presence started")

		while True:
			if (
				"VirtualBox.exe" in (p.name() for p in psutil.process_iter())
				or "VirtualBoxVM.exe" in (p.name() for p in psutil.process_iter())
			) and (sys.platform.startswith("win32")):
				pvars = self.presence_gen()
				# print("-------------------------\npresence_dict\n-------------------------")
				# pprint.pprint(pvars)
				self.RPC.update(
					large_image=pvars["large_image"],
					large_text=pvars["large_text"],
					small_image=pvars["small_image"],
					small_text=pvars["small_text"],
					details=pvars["details"],
					state=pvars["state"],
					start=pvars["start"],
				)
				if self.config["Rich Presence"]["debug"] == "true":
					pprint.pprint(pvars)
					print("--------------------")
			elif sys.platform.startswith("win32"):
				print("VirtualBox is not running")
				self.RPC.clear()
			else:
				pvars = self.presence_gen()
				# print("-------------------------\npresence_dict\n-------------------------")
				# pprint.pprint(pvars)
				self.RPC.update(
					large_image=pvars["large_image"],
					large_text=pvars["large_text"],
					small_image=pvars["small_image"],
					small_text=pvars["small_text"],
					details=pvars["details"],
					state=pvars["state"],
					start=pvars["start"],
				)
				if self.config["Rich Presence"]["debug"] == "true":
					pprint.pprint(pvars)
					print("--------------------")
			time.sleep(15)