默认KVM虚拟机在安装时会通过virbr0接口自动获取一个IP,该IP是通过libvirt管理的dnsmasq服务提供的。而且libvirt在/var/lib/libvirt/dnsmasq/目录有virbr0.macs和virbr0.status两个文件生成。这两个文件拼接后,就可以获取到完整的kvm guest主机的domain name、mac地址、IP地址(仅通过DNSMASQ接口提供的)。

我写了个命令,代码如下:

 1[root@localhost dnsmasq]# cat /usr/local/bin/vhostip.py
 2#!/usr/bin/env python
 3# coding=utf8
 4# ===============================================================================
 5#   Copyright (C) 2016 www.361way.com site All rights reserved.
 6#
 7#   Filename      :vhostip.py
 8#   Author        :yangbk <[email protected]>
 9#   Create Time   :2016-03-06 14:26
10#   Description   :get kvm guest hosts nat dhcp ip
11# ===============================================================================
12import json
13r = open('/var/lib/libvirt/dnsmasq/virbr0.macs')
14domains = json.loads(r.read())
15r = open('/var/lib/libvirt/dnsmasq/virbr0.status')
16ips = json.loads(r.read())
17macs = []
18names = {}
19for domain in domains:
20    mac = domain['macs'][0]
21    macs.append(mac)
22    names[mac] = domain['domain']
23for ipinfo in ips:
24    mac = ipinfo['mac-address']
25    if  mac  in macs:
26      print names[mac],ipinfo['ip-address'],mac

执行效果如下图

kvm-guest-host-ip
kvm-guest-host-ip