首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python将显示主机上的所有VM和ip地址。

问python将显示主机上的所有VM和ip地址。
EN

Stack Overflow用户
提问于 2014-11-18 01:43:46
回答 1查看 2.6K关注 0票数 1

是否有方法显示在特定主机上运行的VM的ip地址。如何使用qemu挂钩查看主机中所有已注册的vm。一种可能的方法是从主机的NIC中嗅出数据包。如何从源ip地址和目标ip地址过滤广播ip地址。有人能提出一个可能的方法来实现这一点吗。我不会对VM使用静态ip地址。python中的脚本将有很大帮助。或者即使是一个想法也会被感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-18 04:08:46

好吧,有几种方法你可以做到。然而,最简单的方法是使用virsh命令行工具

这是特定于系统的,但是在Redhat上,您可以安装libvirt-client包来获取/usr/bin/virsh。

这里有一篇介绍如何将客人的MAC地址映射到他们的IP的文章使用arp和grep的组合。

在libvirt-python中也有一些获取这些信息的方法,但是它的代码要多得多。下面是一个使用libvirt连接到管理程序的示例。

编辑:这里有一些真正未经测试的Python,它应该给您一个开始,但需要一些修改,并玩到100%的工作(可能)

代码语言:javascript
复制
import libvirt  # To connect to the hypervisor
import re
import subprocess


# Connect to your local hypervisor. See https://libvirt.org/uri.html
#    for different URI's where you'd replace `None` with your
#    connection URI (like `qemu://system`)
conn = libvirt.openReadOnly(None)  # Open the hypervisor in read-only mode
# conn = libvirt.open(None)  # Open the default hypervisor in read-write mode (require
if conn == None:
    raise Exception('Failed to open connection to the hypervisor')

try:  # getting a list of all domains (by ID) on the host
    domains = conn.listDomainsID()
except:
    raise Exception('Failed to find any domains')

for domain_id in domains:
    # Open that vm
    this_vm = conn.lookupById(domain_id)
    # Grab the MAC Address from the XML definition
    #     using a regex, which may appear multiple times in the XML
    mac_addresses = re.search(r"<mac address='([A-Z0-9:]+)'", vm.XMLDesc(0)).groups()

    for mac_address in mac_addresses:
        # Now, use subprocess to lookup that macaddress in the
        #      ARP tables of the host.
        process = subprocess.Popen(['/sbin/arp', '-a'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        process.wait()  # Wait for it to finish with the command
        for line in process.stdout:
            if mac_address in line:
                ip_address = re.search(r'(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})', line)
                print 'VM {0} with MAC Address {1} is using IP {2}'.format(
                    vm.name(), mac_address, ip_address.groups(0)[0]
                )
             else:
                # Unknown IP Address from the ARP tables! Handle this somehow...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26985199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档