Skip to content

Instantly share code, notes, and snippets.

@nothingmuch
Created October 11, 2010 23:30
Show Gist options
  • Select an option

  • Save nothingmuch/621409 to your computer and use it in GitHub Desktop.

Select an option

Save nothingmuch/621409 to your computer and use it in GitHub Desktop.
#!/bin/bash
VM="$( basename "$0" )"
if [ -n "$1" ]; then
# explicit control of the VM, e.g. `blah stop`
# useful commands are 'pause', 'resume', 'stop', etc
case "$1" in
status) VBoxManage showvminfo "$VM" | grep -i state ;;
*) VBoxManage controlvm "$VM" ${1/stop/acpipowerbutton} ;; # much easier to type
esac
else
# otherwise just make sure it's up and provide a shell
# boot the virtual machine in headless mode unless it's already running
# note that there is a race condition if the machine is in the process of
# powering down
VBoxManage showvminfo --machinereadable "$VM" | grep -q 'VMState="running"' || \
VBoxManage startvm "$VM" -type vrdp;
# each VM has an SSH config like this:
# Host $VM
# Hostname localhost
# Port 2222 # VBoxManage modifyvm "$VM" --natpf1 ...
# changing ssh port forwarding doesn't require restarting the VM (whereas
# fiddling with VirtualBox port forwarding does). The following section
# should probably just be a per VM include, but for my needs it does the
# job as is.
# ControlMaster works nicely with a global 'ControlPath /tmp/%r@%h:%p' in
# my ~/.ssh/config this means the port forwarding stays up no matter how
# many shells I open and close (unlike ControlMaster auto in the config)
# this loop quietly waits till sshd is up
until nc -z localhost 3000 >/dev/null; do
echo -n "."
ssh -N -f -q \
-L 3000:localhost:3000 \
-o ConnectTimeout=1 \
-o ControlMaster=yes \
"$VM" && echo;
done
# finally, start a shell
exec ssh "$VM"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment