获取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接口提供的)。

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

[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 <itybku@139.com>
#   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

执行效果如下图

kvm-guest-host-ip




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

分类: 虚拟化云和自动化 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.