Skip to content

Instantly share code, notes, and snippets.

@heywoodlh
Created May 8, 2017 14:40
Show Gist options
  • Save heywoodlh/5c9046e6670929619ec35d5bc69e22eb to your computer and use it in GitHub Desktop.
Save heywoodlh/5c9046e6670929619ec35d5bc69e22eb to your computer and use it in GitHub Desktop.
headless-vbox script
#!/usr/bin/env bash
#Requirements:
# 1. ssh needs to be running on vm
# 2. VM_NAME and USER variable need to be set
#Set these variables (VM_NAME should equal the name of your virtualbox vm, USER should equal the name of your vm username)
VM_NAME=""
USER=""
SSH_PORT="3022"
# Set var for consistent path
SCRIPT=$(readlink -f $0)
# Absolute path to the script
SCRIPT_LOCATION=$(dirname $SCRIPT)
LISTFILE_LOCATION="$SCRIPT_LOCATION/list.txt"
if [ "$VM_NAME" == "" ]
then
echo "Please set the VM_NAME variable in $0 script"
exit 1
elif [ "$USER" == "" ]
then
echo "Please set the USER variable in $0 script"
exit 1
fi
#Check if VM_NAME variable is set to a valid value
if ! vboxmanage list vms | grep "$VM_NAME"
then
echo "Please set valid name for VM_NAME variable in $0 script"
exit 1
fi
#Various tests to see if port is already occupied by another VM
if [ -e "$LISTFILE_LOCATION" ] && grep "$SSH_PORT" "$LISTFILE_LOCATION" && ! grep "$VM_NAME" "$LISTFILE_LOCATION"
then
echo "Please set another value for SSH_PORT variable, port $SSH_PORT is currently used"
exit 1
elif [ -e "$LISTFILE_LOCATION" ] && ! grep "$SSH_PORT" "$LISTFILE_LOCATION" && ! grep "$VM_NAME" "$LISTFILE_LOCATION"
then
echo "$VM_NAME = $SSH_PORT" >> "$LISTFILE_LOCATION"
fi
#Check if ssh is being forwarded -- if not, then set rule
if ! VBoxManage showvminfo "$VM_NAME" | grep "Rule" | grep "ssh" | grep "$SSH_PORT"
then
VBoxManage modifyvm "$VM_NAME" --natpf1 "ssh,tcp,,$SSH_PORT,,22"
fi
#Check if vm is powered on
if vboxmanage showvminfo "$VM_NAME" | grep "State:" | grep "powered off"
then
VBoxManage startvm "$VM_NAME" --type headless
echo "Giving VM 30 seconds to start"
sleep 30
echo "Attempting to SSH into VM $VM_NAME"
sleep 2
fi
#SSH into VM
ssh -p "$SSH_PORT" "$USER"@127.0.0.1
#Suggest shutdown on ssh exit
echo "Shutdown $VM_NAME VM? (y/n)"
read RESPONSE
if [ "$RESPONSE" == "y" ]
then
VBoxManage controlvm "$VM_NAME" acpipowerbutton
exit 0
else
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment