Working with Libvirt using Python

Today I decide to toy around with a KVM server we have running in house for testing. I started by using the libvirt Documentation, but it was very limited and I had to do some trial and error. I will go over a few basic things I learned using the libvirt Python module:

Normally we us virt-manager to connect to our KVM instances, and the authentication is tunnled over SSH (using SSH Keys) and QEMU . First things first I had to learn how to connect with the same method we used in virt-manager :

>>> import libvirt
>>> conn ="qemu+ssh://root@")
>>> conn
<libvirt.virConnect instance at 0x2b518c0>

Using the open function I was able to successfully connect to our Hypervisor:

>>> conn.getHostname()

From here I need only see our running virtual machines, and how to interact with them. I noticed two separate function the listDefinedDomains() and listDomainsID() .

These two functions do two separate things, first lets go over listDefinedDomains() , this function will return a list of offline guest by name:

>>> conn.listDefinedDomains()
['rawhide', 'el4-i386', 'el5-64', 'el6-64', ....]

Where as listDomainsID() will return a list of online devices by ID:

>>> conn.listDomainsID()
[1, 2, 10, 3, 17, 7, 9, 8, 5, 6]

Once connected to the Domain you can get its name:

>>> for i in conn.listDomainsID():
...     print conn.lookupByID(i).name()

And as you would expect you can connect to either offline or online domains by using their name:

>>> dom = conn.lookupByName('build01-dev')
>>> dom
<libvirt.virDomain instance at 0x2b82c68>

Now that we understand the process of connecting to our Hypervisor and parsing our Domains, lets go over how to start and stop these Domains, or as libvirt calls it create and destroy.

Lets start out with a offline (or destroyed) domain:

>>> dom = conn.lookupByName('rawhide')
>>> dom.isActive()

To bring this Domain online we need to use the create() function:

>>> dom.create()
>>> dom.isActive()

And to power it down you would destroy() it:

>>> dom.destroy()
>>> dom.isActive()

I hope this helped out a few of you out there, I know this was rather confusion when I first started messing around with it.