Skip to main content

Utilize the python libvirt API to start and stop qemu-kvm machines in a blocking fashion

Project description


I wanted to start and stop individual libvirt virtual machines with a systemd unit.

Calling virsh start %i or virsh stop %i from the unit doesn't cut it. This is because it doesn't block while shutting down so you don't know if the machine is really down unless you wrap it all in a bash script and employ a dirty hack along the lines of virsh list | grep myVM.

Starting a machine is also challenging because virsh start uses exit status 1 for multiple error conditions, including "machine is already running".

The purpose of this script is to start / stop a given virtual machine through the libvirt python bindings in a way that is easily consumable from systemd. This means I try to handle the "already running" case gracefully. Shutting down happens in a blocking fashion, with the option to yank the virtual power cord from the machine in case it ignores our polite requests.

I also took the opportunity to issue shutdown requests every second until the machine is down. This should be unnecessary when the virtual machine has the libvirt guest agent running, but it can sometimes help to convince windows to really shut down instead of asking "really shutdown?" on the virtual console with nobody around to click ok.

Example systemd unit file:

Description=virsh start / stop %i

ExecStart=/opt/ --machine %i --state started
ExecStop=/opt/ --machine %i --state stopped --timeout 80


Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for virsh-start-stop, version 0.0.1
Filename, size File type Python version Upload date Hashes
Filename, size virsh_start_stop-0.0.1-py3.6.egg (5.4 kB) File type Egg Python version 3.6 Upload date Hashes View
Filename, size virsh_start_stop-0.0.1-py3-none-any.whl (4.9 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size virsh_start_stop-0.0.1.tar.gz (5.6 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page