#!/bin/zsh autoload colors colors if [ "$#" -ne 2 ]; then echo "Usage: $0 {boot,halt,reboot,shutdown,start,stop} {libvirt VM}" exit 1 fi function vm_boot() { if virsh start $1 1>/dev/null 2>/dev/null; then echo "$fg_bold[green]Starting VM: $fg_bold[white]$1$reset_color" until nc -z -w 60 $1 22 2>/dev/null; do sleep 1 done fi } function vm_shutdown() { if virsh shutdown $1 1>/dev/null 2>/dev/null; then echo "$fg_bold[red]Stopping VM: $fg_bold[white]$1$reset_color" while nc -z -w 60 $1 22 2>/dev/null; do sleep 1 done while virsh list --name | grep $1 >/dev/null; do sleep 1 done fi } machines=$(virsh list --all --name) if [[ ${machines[(ie)$2]} -le ${#machines} ]]; then case $1 in "boot" | "start") vm_boot $2 ;; "shutdown" | "stop" | "halt") vm_shutdown $2 ;; "reboot") vm_shutdown $2 sleep 1 vm_boot $2 ;; *) echo "Boot, reboot, or shudown?" exit 1 ;; esac fi