From b1fa0acd1ffbdf78dd8cdf12cdc3249f18b09918 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Mon, 29 Nov 2021 15:44:21 -0500 Subject: [PATCH] Create a vm.zsh command With subcommands to boot, reboot, or shutdown machines. Also, output in color. Signed-off-by: Anna Schumaker --- completions/_vm.zsh | 7 +++++++ vm.zsh | 46 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 completions/_vm.zsh create mode 100755 vm.zsh diff --git a/completions/_vm.zsh b/completions/_vm.zsh new file mode 100644 index 0000000..a1d9566 --- /dev/null +++ b/completions/_vm.zsh @@ -0,0 +1,7 @@ +#compdef vm.zsh + +function _vm.zsh() { + _arguments \ + '1:operation:(boot halt reboot shutdown start stop)' \ + ':virtual machine:($(virsh list --all --name))' +} diff --git a/vm.zsh b/vm.zsh new file mode 100755 index 0000000..8869558 --- /dev/null +++ b/vm.zsh @@ -0,0 +1,46 @@ +#!/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