Skip to content

Instantly share code, notes, and snippets.

@omeid
Created December 1, 2013 10:08
Show Gist options
  • Save omeid/7730876 to your computer and use it in GitHub Desktop.
Save omeid/7730876 to your computer and use it in GitHub Desktop.
VirtualBox Manager
#!/bin/bash
function vm {
function vm_status {
return $(vboxmanage list runningvms | grep "$1" &> /dev/null);
}
function vm_start {
vboxheadless -s "$1" &> /dev/null & echo "Server is going up..."
# VBoxManage startvm "$1" --type headless &> /dev/null & echo "Server is going up..."
}
function vm_control {
VBoxManage controlvm $1 $2
}
function vm_ssh {
if ! vm_status "$1" ; then
vm_start "$1"
fi;
local user=$(whoami)
local ssh_params="-Y"
local host="$1"
local user_host=""
case "$3" in
*@*)
user_host="$3"
host=${3##*@}
;;
"")
user_host="$user@$host"
;;
*)
user_host="$3@$host"
;;
esac
echo "Waiting for SSH @ $host:22";
until ncat "$host" 22 --send-only --nsock-engine select </dev/null &> /dev/null;
do printf '.';
done;
echo "" #Empty line for the return.
echo "Connecting to $user_host:22"
echo "" #Empty line for the ssh.
ssh -Y "$ssh_params" ${@:4} "$user_host"
}
function vm_rdesktop {
if ! vm_status "$1" ; then
vm_start "$1"
fi;
rdesktop "localhost:"$(VBoxManage showvminfo $1|awk '/VRDE port/ { print $3}') & echo "rdesktop started. PID: "$!
}
if ! vboxmanage list vms | grep -F "$1" &> /dev/null; then
echo "VM does not exist or is not registered."
return 0
fi
case "$2" in
status)
if vm_status "$1"; then
echo "$1 is up."
else
echo "$1 is down."
fi
return 0
;;
start)
if vm_status "$1" ; then
echo "Server is already up."
return 0;
else
vm_start "$1"
return 0
fi
;;
ssh)
vm_ssh "$@"
return 0
;;
down)
if ! vm_status "$1"; then
echo "VM is down."
else
vm_control "$1 acpipowerbutton"
fi
;;
control)
if ! vm_status "$1"; then
echo "VM is down."
return 0
fi
vm_control "$1" "$3"
return 0
;;
rdesktop)
vm_rdesktop "$1"
return 0
;;
*)
echo "using Defualt option (SSH).. (type <C-c> to abort)"
for i in {1..3}; do printf "."; sleep 1; done;
vm_ssh "$@"
return 0
;;
esac
}
function _vm {
local cur=${COMP_WORDS[COMP_CWORD]}
local prev=${COMP_WORDS[COMP_CWORD-1]}
case "$prev" in
vm)
COMPREPLY=( $(compgen -W "$(vboxmanage list vms | awk '{gsub(/"/,""); print $1}' )" -- $cur) )
return 0
;;
control)
COMPREPLY=( $(compgen -W "pause resume reset poweroff savestate acpipowerbutton acpisleepbutton " -- $cur) )
return 0
;;
ssh)
COMPREPLY=($( compgen -u -- "$cur" ))
return 0
;;
esac
# Keys ?
COMPREPLY=( $(compgen -W "start down ssh control status rdesktop" -- $cur) )
}
complete -F _vm vm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment