Scripting Libvirt with Python

Just a quick script that I wrote while playing around with Libvirt. The libvirt API comes with some Python bindings:

So I thought I’d write a little script to look for VMs with a particular MAC address.  First you have to establish a connection to the libvirt server after importing the libvirt library:

import libvirt 

conn = libvirt.openReadOnly('qemu:///system')

This gives you the connection. The I wrote a function to go find the MAC address among all the domains (VMs) in the system. One thing to note with the Python API, when you get a list of all the domains from the server, can only get them listed by their ID numbres (the C API can get a list of names), so if you want to get a pointer to the actual domain object, or to the name you have to do a lookup. That’s what I did with the map function, to translate all the IDs into domains:

import xml.etree.ElementTree as ET

def findDomainWithMac(conn, addr):
    domlist = map(conn.lookupByID, conn.listDomainsID())
    for dom in domlist:
        root = ET.fromstring(dom.XMLDesc())
        searchString = "./devices/interface/mac[@address='{0}']".format(addr)
        if (root.find(searchString) is not None):
            return dom

I couldn’t find a way to directly query for the MAC address of the interfaces, so I ended up grabbing the XML for the domain, parsing it with ElementTree, and looking for a matching MAC address. Just a quick little script, but enough to get started with the Libvirt APIs. Here’s the whole script:

One thought on “Scripting Libvirt with Python

  1. Nick Garvey says:

    This didn’t work as is for me. XMLDesc takes two arguments, the domain and any flags. The domain is covered by the “dom” in “dom.XMLDesc()”, but the flags argument is needed. I passed a 0 and things worked.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s