获取kvm虚拟机NAT接口DHCP IP

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



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



<br />
[root@localhost dnsmasq]# cat /usr/local/bin/vhostip.py
#!/usr/bin/env python
# coding=utf8
# ===============================================================================
#   Copyright (C) 2016 www.361way.com site All rights reserved.
#
#   Filename      :vhostip.py
#   Author        :yangbk 
#   Create Time   :2016-03-06 14:26
#   Description   :get kvm guest hosts nat dhcp ip
# ===============================================================================
import json
r = open('/var/lib/libvirt/dnsmasq/virbr0.macs')
domains = json.loads(r.read())
r = open('/var/lib/libvirt/dnsmasq/virbr0.status')
ips = json.loads(r.read())
macs = []
names = {}
for domain in domains:
    mac = domain['macs'][0]
    macs.append(mac)
    names[mac] = domain['domain']
for ipinfo in ips:
    mac = ipinfo['mac-address']
    if  mac  in macs:
      print names[mac],ipinfo['ip-address'],mac
执行效果如下图



<img src="https://www.361way.com/wp-content/uploads/2016/03/kvm-guest-host-ip.png" width="352" height="92" title="kvm-guest-host-ip" alt="kvm-guest-host-ip" />

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注