Skip to content

Instantly share code, notes, and snippets.

@cedriczirtacic
Last active April 11, 2022 21:27
Show Gist options
  • Save cedriczirtacic/65286ac8548f3df427046562289b5d51 to your computer and use it in GitHub Desktop.
Save cedriczirtacic/65286ac8548f3df427046562289b5d51 to your computer and use it in GitHub Desktop.
quick VBox (headless) admin script
#!/bin/bash
# cedric
# XXX: this is how I prefer to stop a VM, change this at will
PREFERRED_STOP_METHOD="acpipowerbutton"
function perror() { echo -e $@ 1>&2; }
function vm_exists() {
local VM=$1
VBoxManage showvminfo "${VM}" >/dev/null 2>&1
return $?
}
#Â ACTIONS
function start() {
echo "[INFO] Starting \`${VMNAME}\`..."
(
cd /tmp && \
nohup VBoxHeadless -startvm "${VMNAME}" &
) > /dev/null 2>&1
return 0
}
function stop() {
echo "[INFO] Stopping \`${VMNAME}\`..."
VBoxManage controlvm "${VMNAME}" ${PREFERRED_STOP_METHOD}
return 0
}
function pause() {
echo "[INFO] Pausing \`${VMNAME}\`..."
VBoxManage controlvm "${VMNAME}" pause
return 0
}
function resume() {
echo "[INFO] Resuming \`${VMNAME}\`..."
VBoxManage controlvm "${VMNAME}" resume
return 0
}
function status() {
local STATUS=$( VBoxManage showvminfo "${VMNAME}"|egrep '^State:'|sed -E 's/State:\s+//g' )
printf "[INFO] %s\n" "$STATUS"
return 0
}
function _is_status() {
local DESIRED=$1
status | grep -q "${DESIRED}" >/dev/null
return $?
}
if [[ ${#@} -lt 2 ]];then
if [ ${#@} -eq 1 ] && [ "$1" == "list" ];then
VBoxManage list vms
exit 0
fi
perror "Usage:\t$0 <vm> <start|stop|pause|resume|status>"
perror "\t$0 list"
exit 1
fi
VMNAME=$1
ACTION=$2
if ! vm_exists "$VMNAME";then
perror "[ERROR] VM \`${VMNAME}\` doesn't exists."
exit 2
fi
case $ACTION in
stop)
_is_status "running"
if [ $? -ne 0 ];then
perror "[ERROR] VM is not running!"
exit 3
fi
stop
;;
start)
_is_status "powered off"
if [ $? -ne 0 ];then
perror "[ERROR] VM is not powered off!"
exit 3
fi
start
;;
pause)
_is_status "running"
if [ $? -ne 0 ];then
perror "[ERROR] VM is not running!"
exit 3
fi
pause
;;
resume)
_is_status "paused"
if [ $? -ne 0 ];then
perror "[ERROR] VM is not paused!"
exit 3
fi
resume
;;
status)
status
;;
*)
perror "[ERROR] Unexistent action."
exit 3
;;
esac
exit 0
#!/bin/bash
VMS=$( ./vm_admin.sh list | grep -Eo "\"(.+?)\"" | tr -d '"')
IFS=$'\n'
for vm in ${VMS[*]};do
echo -en "VM: $vm\n\t"
./vm_admin.sh "${vm}" status
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment