libvirt-python binding for Libvirt API

12.2.0 · active · verified Thu Apr 16

The `libvirt-python` library provides a Pythonic binding to the C API of libvirt, the open-source virtualization management library. It allows Python applications to manage virtual machines, storage, and networking on various hypervisors like KVM, QEMU, and Xen. Currently at version 12.2.0, it generally tracks the libvirt C library's release cycle, typically seeing multiple updates per year.

Common errors

Warnings

Install

Imports

Quickstart

Connects to the local QEMU/KVM hypervisor, prints its hostname and libvirt version, then closes the connection. This demonstrates basic connection and resource management.

import libvirt
import sys

# Connect to the default QEMU/KVM hypervisor.
# 'qemu:///system' requires appropriate permissions (e.g., user in 'libvirt' group or root).
# For user-session hypervisor, try 'qemu:///session'.
try:
    conn = libvirt.open("qemu:///system")
    if conn is None:
        print('Failed to open connection to qemu:///system', file=sys.stderr)
        sys.exit(1)
except libvirt.libvirtError as e:
    print(f'Failed to open connection: {e}', file=sys.stderr)
    sys.exit(1)

print(f"Successfully connected to libvirt. Hypervisor: {conn.getHostname()}")

# Example: Get and print libvirt version
print(f"Libvirt version: {conn.getVersion()}")

# Always close the connection
conn.close()

view raw JSON →