#!/usr/bin/env python
# Need python-libvirt
from __future__ import print_function, unicode_literals
import sys
import libvirt
from xml.etree import ElementTree
from subprocess import check_output
import re
class LibVirtManager(object):
def __init__(self, uri):
self.conn = libvirt.open(uri)
def createDomainFromXMLFile(self, xmlFile, flags):
"""
if the libvirt.VIR_DOMAIN_START_PAUSED flags is set, the guest
domain will be started, but its CPUs will remain paused.
"""
xml = open(xmlFile).read()
self.conn.createXML(xml, flags)
def info(self, dom):
infos = dom.info()
print("""id = {dom_id}
name = {name}
state = {state}
max memory = {memory_size}
number of virt cpus = {cpus}
cpu time (in ns) = {cpu_time}
""".format(
dom_id=dom.ID(), name=dom.name(), state=infos[0],
memory_size=infos[1], cpus=infos[3], cpu_time=infos[2]
))
def __getattr__(self, attr):
if hasattr(self.conn, attr):
return getattr(self.conn, attr)
raise AttributeError
def main():
if not len(sys.argv[1:]):
print("Need VM name.")
sys.exit(-1)
arp_result = check_output(['arp', '-an'])
if arp_result:
arp_result = arp_result.split('\n')
else:
arp_result = ""
pattern = re.compile('\?\ \((?P<ip>.+)\).*')
manager = LibVirtManager("qemu:///system")
domain = manager.lookupByName(sys.argv[1])
for item in dir(domain):
if 'XML' in item:
print(item)
results = []
tree=ElementTree.fromstring(domain.XMLDesc(0))
for target in tree.findall("devices/interface/mac"):
macaddress = target.get('address')
for line in arp_result:
if not macaddress in line:
continue
matched = pattern.search(line)
if matched:
results.append(matched.group("ip"))
if len(results):
print(results)
else:
print("Not found")
if __name__ == "__main__":
main()