import os
import re
import sys
import uuid
import subprocess
from datetime import datetime
from functools import partial
from subprocess import CalledProcessError
def native_cmd(cmd):
"""Returns the output of a native command on a give system.
NOTE: Results may contain white space charaters at end of lines.
"""
return subprocess.check_output(cmd, shell=True).decode()
# native_cmd("echo %USERPROFILE%")
# os.path.expandvars('%USERPROFILE%')
# os.path.expandvars('%PROGRAMFILES%')
def use_nt_exe(exe_path, cmd):
"""Return output of an exe program given the path and command
NOTE: For using Windows systems."""
return native_cmd('"{}" '.format(exe_path)+cmd)
def load_nt_exe(path):
"""Return a partial function form an exe path.
"""
return partial(use_nt_exe, path)
if os.name == 'nt':
vbman_path = os.path.join("%PROGRAMFILES%", "Oracle", "VirtualBox", "VBoxManage.exe")
vbman_path = os.path.expandvars(vbman_path)
if os.path.exists(vbman_path):
vbman = load_nt_exe(vbman_path)
vbman.__doc__ = vbman('')
print(vbman('list vms'))
vbman()
# vbman_man = vbman('').replace('\r', '')
# print(vbman_man)
# res = re.findall('Commands:(.+)', vbman_man, flags=re.DOTALL)[0]
# res = list(filter(lambda x:len(x)>0, res.split('\n')))
# cmds = []
# n = 0
# for i in res[1:]:
# if i[:2] == ' ' and n == 0:
# cmds.append(i)
# # Stop as soon as a line without two spaces is found.
# else:
# n+=1
# # list(filter(lambda x:x[:3] != ' ', cmds))
# for i in cmds:
# if i[:3] != ' ':
# cmd_str = i.strip().split()[0]
# print(cmd_str)
# class VBMan(object):
# def __init__(self):
# pass
# setattr(VBMan, 'thing', 'hello')
# VBMan.thing
re.split(':\s', 'D:')
['D:']
# def showvninfo(name, **kwargs):
# cmd="showvminfo {} --details".format(name)
# result = vbman(cmd)
# if '\r' in result:
# result.replace('\r', '')
# return result
# print(showvninfo('win7ult_master_v0'))
def showvminfo_dict(name):
cmd="showvminfo {} --details".format(name)
result = vbman(cmd)
if '\r' in result:
result = result.replace('\r', '')
result = result.split('\n')
result = list(map(lambda x:re.split(':\s', x), result))
result = [list(map(lambda x: x.strip(), i)) for i in result]
result = list(filter(lambda x:len(x)==2, result))
result = list(filter(lambda x:type(x)==list, result))
result = dict(result)
return result
showvminfo_dict('win7ult_master_v0')
{'2D Video Acceleration': 'off', '3D Acceleration': 'off', 'ACPI': 'on', 'APIC': 'on', 'Allow Tracing to Access VM': 'off', 'Audio capture': 'disabled', 'Audio playback': 'disabled', 'Autostart Delay': '0', 'Autostart Enabled': 'off', 'BIOS APIC mode': 'APIC', 'Bandwidth groups': '<none>', 'Boot Device (1)': 'Floppy', 'Boot Device (2)': 'DVD', 'Boot Device (3)': 'HardDisk', 'Boot Device (4)': 'Not Assigned', 'Boot menu mode': 'message and menu', 'CPU exec cap': '100%', 'CPUID Portability Level': '0', 'CPUID overrides': 'None', 'Capture FPS': '25', 'Capture dimensions': '1024x768', 'Capture file': 'D:\\virtual_machines(windows)\\win7ult_master_v0\\win7ult_master_v0.webm', 'Capture options': 'ac_enabled=false', 'Capture rate': '512 kbps', 'Capture screens': '0', 'Capturing': 'not active', 'Chipset': 'piix3', 'Clipboard Mode': 'disabled', 'Config file': 'D:\\virtual_machines(windows)\\win7ult_master_v0\\win7ult_master_v0.vbox', 'Configured memory balloon size': '0 MB', 'Default Frontend': '', 'Drag and drop Mode': 'disabled', 'EHCI': 'disabled', 'Effective Paravirt. Provider': 'HyperV', 'Firmware': 'BIOS', 'Groups': '/', 'Guest OS': 'Windows 7 (64-bit)', 'HPET': 'off', 'Hardw. virt.ext': 'on', 'Hardware UUID': '38cb7060-59e4-4225-83e4-6be58b335765', 'IOAPIC': 'on', 'Keyboard Device': 'PS/2 Keyboard', 'LPT 1': 'disabled', 'LPT 2': 'disabled', 'Large Pages': 'on', 'Log folder': 'D:\\virtual_machines(windows)\\win7ult_master_v0\\Logs', 'Long Mode': 'on', 'Memory size': '8320MB', 'Monitor count': '1', 'NIC 2': 'disabled', 'NIC 3': 'disabled', 'NIC 4': 'disabled', 'NIC 5': 'disabled', 'NIC 6': 'disabled', 'NIC 7': 'disabled', 'NIC 8': 'disabled', 'Name': 'win7ult_master_v0', 'Nested Paging': 'on', 'Number of CPUs': '4', 'PAE': 'on', 'Page Fusion': 'off', 'Paravirt. Provider': 'Default', 'Pointing Device': 'PS/2 Mouse', 'RTC': 'local time', 'SATA (1, 0)': 'Empty', 'Shared folders': '<none>', 'Snapshot folder': 'D:\\virtual_machines(windows)\\win7ult_master_v0\\Snapshots', 'State': 'powered off (since 2017-11-21T15:55:31.000000000)', 'Storage Controller Bootable (0)': 'on', 'Storage Controller Instance Number (0)': '0', 'Storage Controller Max Port Count (0)': '30', 'Storage Controller Name (0)': 'SATA', 'Storage Controller Port Count (0)': '30', 'Storage Controller Type (0)': 'IntelAhci', 'Teleporter Address': '', 'Teleporter Enabled': 'off', 'Teleporter Password': '', 'Teleporter Port': '0', 'Time offset': '0ms', 'Tracing Configuration': '', 'Tracing Enabled': 'off', 'Triple Fault Reset': 'off', 'UART 1': 'disabled', 'UART 2': 'disabled', 'UART 3': 'disabled', 'UART 4': 'disabled', 'USB': 'disabled', 'UUID': 'd33cdcb8-376c-469e-9d0c-8ca7839fb896', 'VRAM size': '8MB', 'VRDE': 'disabled', 'VT-x VPID': 'on', 'VT-x unr. exec.': 'on', 'X2APIC': 'off', 'XHCI': 'disabled'}
# Create and register the vbox.
vbman('createvm --name "win7ult_master_v0" --ostype Windows7_64 --register')
"Virtual machine 'win7ult_master_v0' is created and registered.\r\nUUID: d33cdcb8-376c-469e-9d0c-8ca7839fb896\r\nSettings file: 'D:\\virtual_machines(windows)\\win7ult_master_v0\\win7ult_master_v0.vbox'\r\n"
# Create the SATA controller
vbman('storagectl win7ult_master_v0 --name SATA --add sata --controller IntelAHCI')
''
# Create the blank 64gb vdi
vbman('createmedium --filename "D:\\virtual_machines(windows)\\win7ult_master_v0\\win7ult_master_v0.vdi" --size 64000')
'Medium created. UUID: 663ff20b-4de0-4fc0-b64a-f1008e48e413\r\n'
# Attach the blank vdi
vbman('storageattach win7ult_master_v0 --storagectl SATA --port 0 --type hdd --medium 663ff20b-4de0-4fc0-b64a-f1008e48e413')
''
# Attach install dvd
vbman('storageattach win7ult_master_v0 --storagectl SATA --port 1 --type dvddrive --medium emptydrive')
''
new_mem_size = 128*65
# Set memory size.
vbman('modifyvm win7ult_master_v0 --memory {}'.format(new_mem_size))
# Set number of Processors.
vbman('modifyvm win7ult_master_v0 --cpus 4')
''
new_vram = 64
# Set Video Memory size.
vbman('modifyvm win7ult_master_v0 --vram {}'.format(new_vram))
''
vm_info = showvminfo_dict("win7ult_master_v0")
print(vm_info["Number of CPUs"])
print(vm_info['Memory size'])
4 8320MB
def get_vm_loc(machine_name):
cpath = showvminfo_dict(machine_name)["Config file"]
vm_loc = os.path.split(cpath)[0]
return vm_loc
# get_vm_loc("win7ult_master_v0")
yes = {'yes','y'}
no = {'no','n'}
def change_hardware_uuid(machine_name):
try:
machineinfo = vm_info_dict(machine_name)
except CalledProcessError:
print('{} not found'.format(machine_name))
current_hardware_uuid = machineinfo['Hardware UUID']
new_hardware_uuid = str(uuid.uuid4())
prompt_str = "Sure want to change {} Hardware UUID?".format(machine_name)
choice = input(prompt=prompt_str).lower()
if choice in yes:
now = '{}'.format(datetime.now())
chng_log = '{}: {} hardware uuid was changed from {} to {}\n'.format(now, machine_name,
current_hardware_uuid, new_hardware_uuid)
chng_log_path = os.path.join(get_vm_loc(machine_name), 'hardware_uuid_change_log.txt')
f = open(chng_log_path, 'a+')
f.write(chng_log)
f.close()
cmd = 'modifyvm {} --hardwareuuid {}'.format(machineinfo['UUID'], new_hardware_uuid)
vbman(cmd)
print('hardware uuid has been changed to {}'.format(new_hardware_uuid))
if choice in no:
print('operation aborted')
pass
else:
pass
return
change_hardware_uuid('win7ult_master_v0')
'D:\\virtual_machines(windows)\\win7ult_master_v0'