python 在https://rwmj.wordpress.com/2010/10/26/tip-find-the-ip-address-of-a-virtual-machine/中将端口“virt

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在https://rwmj.wordpress.com/2010/10/26/tip-find-the-ip-address-of-a-virtual-machine/中将端口“virt相关的知识,希望对你有一定的参考价值。

#!/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()

以上是关于python 在https://rwmj.wordpress.com/2010/10/26/tip-find-the-ip-address-of-a-virtual-machine/中将端口“virt的主要内容,如果未能解决你的问题,请参考以下文章

在树莓派上的python3

如何在命令行里运行python脚本

如何在windows cmd下运行python

python2与python3在windows下共存

保存了python文件怎样在python中拿出来

python编程应用在哪些行业