#!/usr/bin/env bash HOSTNAME="aca-lab" VMNAME="aca-lab" HOST_PORT=3022 SSH_PORT=22 function cleanup { # Poweroff the machine on exit or failure VBoxManage controlvm "$VMNAME" poweroff } trap cleanup EXIT SIGINT SIGTERM function config { # Setup SSH port forwarding if not setup VBoxManage showvminfo "$VMNAME" | grep -q \ "Rule.*host\ port\ = $HOST_PORT.*guest\ port = $SSH_PORT"; local port_unset=$?; echo "Port: $port_unset" if [[ $port_unset -eq 1 ]]; then echo "Setting SSH port forwarding" echo "VBoxManage modifyvm \"$VMNAME\" --natpf1 \"ssh,tcp,,$HOST_PORT,,$SSH_PORT\"" VBoxManage modifyvm "$VMNAME" --natpf1 "ssh,tcp,,$HOST_PORT,,$SSH_PORT" fi } function init { # Start the VM VBoxManage startvm "$VMNAME" --type headless; local status=$? if [ $status -ne 0 ]; then echo "Failed to start the machine" >&2 exit $status else echo "Booting up, this might take a while..." fi } config; init; ssh $HOSTNAME