QEMU Monitor Protocol Library

0.0.6 · active · verified Wed Apr 15

qemu.qmp is a Python library, built on asyncio, for interacting with QEMU emulators via the QEMU Monitor Protocol (QMP). It enables sending QMP messages to control and query QEMU instances, including the QEMU Guest Agent (QGA) and QEMU Storage Daemon (QSD). The library currently stands at version 0.0.6 and has a release cadence tied to the QEMU project's development, as it was originally split from the QEMU source tree.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a running QEMU instance via its QMP interface (either TCP or UNIX socket) and execute a simple 'query-status' and 'query-version' command. Remember to start your QEMU VM with a QMP monitor enabled (e.g., `-qmp tcp:127.0.0.1:1234,server,nowait`). Environment variables `QEMU_QMP_HOST`, `QEMU_QMP_PORT`, or `QEMU_QMP_UNIX_SOCKET` can be used to configure the connection.

import asyncio
import os
from qemu.qmp import QMPClient

async def main():
    # Replace '127.0.0.1' and '1234' with your QEMU QMP socket address and port.
    # For a UNIX socket, use a path string like '/tmp/qemu-monitor.sock'.
    # Ensure QEMU is started with a QMP monitor, e.g., 
    # qemu-system-x86_64 -qmp tcp:127.0.0.1:1234,server,nowait -enable-kvm ...
    # or
    # qemu-system-x86_64 -qmp unix:/tmp/qemu-monitor.sock,server,nowait -enable-kvm ...
    qmp_host = os.environ.get('QEMU_QMP_HOST', '127.0.0.1')
    qmp_port = int(os.environ.get('QEMU_QMP_PORT', '1234'))
    qmp_socket_path = os.environ.get('QEMU_QMP_UNIX_SOCKET', None)

    qmp = QMPClient('my_vm_instance')

    try:
        if qmp_socket_path:
            print(f"Connecting to QMP UNIX socket: {qmp_socket_path}")
            await qmp.connect(qmp_socket_path)
        else:
            print(f"Connecting to QMP TCP socket: {qmp_host}:{qmp_port}")
            await qmp.connect((qmp_host, qmp_port))

        print("Connected to QEMU QMP.")

        # Example: Execute 'query-status' command
        status_response = await qmp.execute({'execute': 'query-status'})
        print(f"QEMU Status: {status_response}")

        # Example: Execute 'query-version' command
        version_response = await qmp.execute({'execute': 'query-version'})
        print(f"QEMU Version: {version_response}")

    except Exception as e:
        print(f"Error connecting or executing QMP command: {e}")
    finally:
        if qmp.is_connected():
            await qmp.disconnect()
            print("Disconnected from QEMU QMP.")

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →