是否可以显示在特定主机上运行的VM的IP地址。如何使用qemu钩子查看主机中所有已注册的vm。一种可能的方法是嗅探进出主机NIC的数据包。但是如何从源和目标IP地址过滤广播IP地址。任何人都可以建议实现这一目标的可行方法。我没有为VM使用静态IP地址。 python中的脚本将会有很大的帮助。或者甚至一个想法将不胜感激..
答案 0 :(得分:1)
嗯,有几种方法可以做到这一点。但最简单的方法是使用virsh
命令行工具
这是特定于系统的,但在Redhat上,您可以安装libvirt-client
包以获取/usr/bin/virsh
。
Here's a SO article showing how to map the MAC address of a guest to their IP使用arp
和grep
的组合。
有很多方法可以通过libvirt-python
获取部分信息,但代码更多。 Here's an example of using libvirt to connect to your hypervisor
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...