Ever need a list of all the VMs on LIBVIRT systems to paste on your internal Mediawiki? Well here is a short script to do just that and some guides to what you can and can't easily get from the Python LIBVIRT libraries.
We start simply with a list of IPs for some LIBVIRT servers and also assume that this script will be running on a system with SSH keys to the server. A "customtable" style on the wiki makes our table look better.
#!/usr/bin/env python
L = ['192.168.20.5', '192.168.20.6', '192.168.20.7', '192.168.20.8', '192.168.20.9', '192.168.20.10']
print "{| class=\"customtable\""
print "|}"
If you ran this you would get the following output
{| class="customtable"
|}
Adding the library import and a test to see if it is working.
#!/usr/bin/env python
import libvirt
L = ['192.168.20.5', '192.168.20.6', '192.168.20.7', '192.168.20.8', '192.168.20.9', '192.168.20.10']
ip = '192.168.20.5'
print "{| class=\"customtable\""
remoteconnection = libvirt.openReadOnly('qemu+ssh://root@' + ip + '/system')
print "![[%s]] - %s\n|-" % (remoteconnection.getHostname(), ip)
print "|}"
Should give some output like this.
{| class="customtable"
!VH1.virtnet.local - 192.168.20.5
|}
Adding a loop for the VMs
#!/usr/bin/env python
import libvirt
L = ['192.168.20.5', '192.168.20.6', '192.168.20.7', '192.168.20.8', '192.168.20.9', '192.168.20.10']
ip = '192.168.20.5'
usedcpus = 0
usedram = 0
print "{| class=\"customtable\""
remoteconnection = libvirt.openReadOnly('qemu+ssh://root@' + ip + '/system')
print "! colspan=\"3\" | [[%s]] - %s\n|-" % (remoteconnection.getHostname(), ip)
print "!Hostname!!CPUs!!RAM\n|-"
for id in remoteconnection.listDomainsID():
dom = remoteconnection.lookupByID(id)
usedcpus = usedcpus + dom.info()[3]
usedram = usedram + dom.info()[1]
print "|[[%s]]||%s||%sMB\n|-" % (dom.name(), str(dom.info()[3]), str(dom.info()[1] / 1024))
print "! Total \n|%s||%sMB\n|-" % (str(usedcpus), str(usedram / 1024))
print "|}"
And a loop for the IPs.
#!/usr/bin/env python
import libvirt
L = ['192.168.20.5', '192.168.20.6', '192.168.20.7', '192.168.20.8', '192.168.20.9', '192.168.20.10']
print "{| class=\"customtable\""
for ip in L:
usedcpus = 0
usedram = 0
remoteconnection = libvirt.openReadOnly('qemu+ssh://root@' + ip + '/system')
print "! colspan=\"3\" | [[%s]] - %s\n|-" % (remoteconnection.getHostname(), ip)
print "!Hostname!!CPUs!!RAM\n|-"
for id in remoteconnection.listDomainsID():
dom = remoteconnection.lookupByID(id)
usedcpus = usedcpus + dom.info()[3]
usedram = usedram + dom.info()[1]
print "|[[%s]]||%s||%sMB\n|-" % (dom.name(), str(dom.info()[3]), str(dom.info()[1] / 1024))
print "! Total \n|%s||%sMB\n|-" % (str(usedcpus), str(usedram / 1024))
print "|}"