samba
12/20/2012 - 7:00 PM

Virtual Box headless - shell shortcuts

Virtual Box headless - shell shortcuts

#!/bin/bash

# VirtualBox control handler
# OS X shell context (BSD utilities)

# Simplifies VBoxHeadless and VBoxManage calls.
# In my use-case, the primary objective is to

# Usage:
#   vm.sh list                     lists all your VMs
#   eval `vm.sh use "searchtext"`  set the active VM for later commands
#   vm.sh start                    start the VM indicated by ${VM}
#   vm.sh stop                     stop the vm indicated by ${VM}




which VBoxManage >/dev/null || echo "Could not find VBoxManage command !!!" >&2

vm_list_transpose () {
    VBoxManage list $1 | sed -E 's/"(.*)"[ ]+\{([a-z0-9-]+)\}/\2 \1/'
}

vm_list_status () {
    vm_list_transpose $1 | while read uuid name; do
        echo $uuid `vm_get_state $uuid` "\t   " $name
        # echo $uuid $name
    done
}

vm_list_not_running () {
    vm_list_status vms | while read uuid status name; do
        test "$status" != "running" && echo "$uuid $status\t    $name"
    done
}


vm_get_state () {
    VBoxManage showvminfo --machinereadable $1 | grep '^VMState=' | \
        sed -E 's/([A-Za-z0-9_]+)="(.*)"/\2/'
}

vm_do_shutdown () {
# Tells the machine to perform a (somewhat graceful) shutdown, if possible.
    VBoxManage controlvm $1 acpipowerbutton
}

vm_do_suspend () {
# Saves the state to disk, and then shuts down the VM like hibernation.
    VBoxManage controlvm $1 savestate
}

vm_do_pause () {
# Places the machine into a "paused" state so that, preventing CPU usage but
# without saving state to disk. This will retain memory occupation.
    VBoxManage controlvm $1 pause
}

vm_do_resume () {
# Wakes a machine from "paused" state
    VBoxManage controlvm $1 resume
}

vm_do_start () {
# Start a VM in a background state
#   nohup VBoxHeadless -startvm $1 -v config
    VBoxManage startvm $1 --type ${2}
}

vm_do_snapshot () {
# Take a snapshot of the machine.
    VBoxManage snapshot $1 take "Snapshot `date +"%Y-%m-%d %H:%M:%S"`" \
        --description "Automated snapshot on schedule." \
        --uniquename Timestamp
}

vm_get_uuid () {
    vm_list_transpose vms | grep "$@" | cut -c 1-36 | head -n 1
}



vm_control_main () {
    local action=$1; shift 1;
    local vmselected="${1:-$VIRTUALBOX_UUID}";

    case "$action" in
        use) echo "export VIRTUALBOX_UUID=`vm_get_uuid "$@"`";;
        list) vm_list_status vms;;
        listoffline) vm_list_not_running;;
        start) vm_do_start "${vmselected}" "gui";;
        stop) vm_do_shutdown "${vmselected}";;
        bgstart) vm_do_start "${vmselected}" "headless";;
        suspend) vm_do_suspend "${vmselected}";;
        snapshot) vm_do_snapshot "${vmselected}";;
        *) echo "Unknown command: '$action'" >&2;;
    esac
}


vm_control_main "$@"