Skip to content

Instantly share code, notes, and snippets.

@siennathesane
Created July 22, 2021 18:12
Show Gist options
  • Save siennathesane/d82586b09649232c16818c3f4b936478 to your computer and use it in GitHub Desktop.
Save siennathesane/d82586b09649232c16818c3f4b936478 to your computer and use it in GitHub Desktop.
Starts a dev machine on Virtualbox and SSH's into it
#!/bin/bash
set +e
set +x
VM_NAME="$1"
function isInvalid() {
INVALID=$(ipcalc "$1" | grep -c INVALID)
if [ "${INVALID}" -gt 0 ]; then
return 1
else
return 0
fi
}
function guestWait() {
INT_HOST_IP=$1
COUNT=1
local GOOD=1
echo $INT_HOST_IP
while [[ $GOOD -gt 0 ]]; do
sleep 1
INT_HOST_IP=$(VBoxManage guestproperty get "${VM_NAME}" "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{print $2}')
echo -ne "${WAITER}Waited ${COUNT}s for IP from host, IP: ${INT_HOST_IP}"
isInvalid "${INT_HOST_IP}"
GOOD=$?
((COUNT++))
done
HOST_IP=$INT_HOST_IP
echo -e "" # new line
}
echo "Booting host."
VboxManage startvm "${VM_NAME}" --type headless >> /dev/null 2>&1
POWER_ON_EXIT_CODE=$?
HOST_IP=$(VBoxManage guestproperty get "${VM_NAME}" "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{print $2}')
WAITER="\r\033[0K"
if [ $POWER_ON_EXIT_CODE -gt 0 ]; then
echo "Host already awake, checking IP."
isInvalid "${INT_HOST_IP}"
GOOD=$?
if [[ $GOOD -gt 0 ]]; then
guestWait "${HOST_IP}";
fi
else
guestWait "${HOST_IP}"
fi
ssh "${HOST_IP}"
SSH_RET_CODE=$?
if [[ "${SSH_RET_CODE}" -gt 0 ]]; then
echo -e "Bad SSH command"
exit $SSH_RET_CODE
fi
echo -e "Exiting host to save on resources."
VBoxManage controlvm "${VM_NAME}" acpipowerbutton
sleep 5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment