Tuesday, April 28th, 2020 at 8:06am

Bash script to shutdown (and restart) libvirt/qemu/kvm guests

Posted by Jordan Erickson

Today I wrote two simple bash scripts. The first one shuts down all of my running libvirt (+ qemu/kvm) guest virtual machines at once. The second script automates restarting all guests marked as ‘autostart’ in qemu. I’m using these in Debian 10 (Buster).

The reason I made these scripts was to help in automating the upgrade of qemu/kvm/libvirt packages on my host. I use “guests-stop” (1st script) before upgrading host packages and “guests-start” (2nd script) after the upgrade is complete. In my experience it’s good practice to reboot your guest VMs after upgrading virtualization packages. I hope they are of use to others as well. I make no warranty for them but if you look at the code it’s pretty straight forward/harmless considering their intention 🙂 Cheers!

#!/bin/bash
#
# To shut down all libvirt/qemu/kvm guests immediately.
#
/usr/bin/clear
printf %s "Active libvirt guests running:

$(sudo virsh list | tail -n +3 | awk '{print $2}')

"

verify () {
   # Warn about what we're doing here
   read -p "Shut down all libvirt/QEMU/KVM guests (y/n): " yn
   case $yn in

      y) 
         for i in $(sudo virsh list | tail -n +3 | awk '{print $2}')
         do
            echo "Shutting down guest $i..."
            sudo virsh shutdown $i
         done
         # Monitor guest shutdown sequence after a short delay
         sleep 3
         sudo watch -n 1 "virsh list"
      ;;

      n)
         printf %s "Ok.
"
         exit 0
      ;;

      *) verify
      ;;
   esac
}

verify

exit 0
#!/bin/bash
#
# To start all libvirt guests marked as autostart
#
/usr/bin/clear

printf %s "Domains currently marked as autostart:

$(sudo virsh list --all --autostart | tail -n +3 | awk '{print $2}')

"

verify () {
   # Warn about what we're doing here
   read -p "Start all libvirt guests marked as autostart (y/n): " yn
   case $yn in

      y) 
         for i in $(sudo virsh list --all --autostart | tail -n +3 | awk '{print $2}')
         do
            echo "Starting guest $i..."
            sudo virsh start $i
         done
      ;;

      n)
         printf %s "Ok.
"
         exit 0
      ;;

      *) verify
      ;;
   esac
}

verify

exit 0

© 2020 Logical Networking Solutions: Lake and Sonoma County Computer Repair