Last active
January 2, 2020 08:01
-
-
Save ashleykleynhans/58e4728a6ec37deede0fba890e0efa98 to your computer and use it in GitHub Desktop.
Python script to control Headless VirtualBox VMs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3.8 | |
import argparse | |
import os | |
import re | |
parser = argparse.ArgumentParser(prog='vbox', description='CLI for VirtualBox DevBox.') | |
parser.add_argument('--box', nargs='?', const='FNB DevBox #3', default='DevBox', help='VM to start, eg: --box "DevBox"') | |
parser.add_argument('--start', '--on', action='store_true', help='Start') | |
parser.add_argument('--pause', '-p', action='store_true', help='Pause') | |
parser.add_argument('--resume', '-r', action='store_true', help='Resume') | |
parser.add_argument('--poweroff', '--off', '--stop', action='store_true', help='Poweroff') | |
parser.add_argument('--status', action='store_true', help='Status') | |
args = parser.parse_args() | |
if args.start: | |
os.system(f'VBoxManage startvm "{args.box}" --type headless') | |
print(f'Started: {args.box}') | |
elif args.pause: | |
os.system(f'VBoxManage controlvm "{args.box}" pause --type headless') | |
print(f'Paused: {args.box}') | |
elif args.resume: | |
os.system(f'VBoxManage controlvm "{args.box}" resume --type headless') | |
print(f'Resumed: {args.box}') | |
elif args.poweroff: | |
os.system(f'VBoxManage controlvm "{args.box}" poweroff --type headless') | |
print(f'Stopped: {args.box}') | |
elif args.status: | |
cmd = 'VBoxManage list vms -l | grep -e ^Name: -e ^State' | |
vms = os.popen(cmd).read() | |
vms = vms.strip() | |
vms = vms.split('Name:') | |
vms.pop(0) | |
vmdata = '' | |
for vm in vms: | |
vm = vm.strip() | |
if not re.search("^'", vm): | |
vmdata += vm | |
vms = vmdata.split(')') | |
vms.pop() | |
for vm in vms: | |
vm = vm.split("\n") | |
name = vm[0].strip() | |
state = vm[1].strip() | |
matches = re.findall("^State:\s+([\w\s]+) \(", state) | |
state = matches[0] | |
if name == args.box: | |
print(f'{name}: {state}') | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment