def hostname(domain: libvirt.virDomain): try: with suppress_stderr(): hostname = domain.hostname() return hostname except libvirt.libvirtError: macs = [] ifaces = domain.interfaceAddresses( libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE) for (_, val) in ifaces.items(): if val["hwaddr"]: macs.append(val["hwaddr"]) conn = domain.connect() for network in conn.listAllNetworks( libvirt.VIR_CONNECT_LIST_NETWORKS_ACTIVE): for lease in network.DHCPLeases(): for mac in macs: if lease["mac"] == mac: return lease["hostname"]
def libvirt_screenshot(domain: libvirt.virDomain) -> BytesIO: """Takes a screenshot of the vnc connection of the guest. The resulting image file will be in Portable Pixmap format (PPM). """ def handler(_, buff, file_handler): file_handler.write(buff) string = BytesIO() stream = domain.connect().newStream(0) try: domain.screenshot(stream, 0, 0) stream.recvAll(handler, string) except Exception as error: stream.abort() raise RuntimeError("Unable to take screenshot") from error else: stream.finish() return string