KVM libvirt在虚拟机上使用DHCP分配静态来宾IP地址

时间:2020-01-09 10:41:42  来源:igfitidea点击:

我在Linux操作系统上使用KVM/libvirt,如何使用dnsmasq dhcpd服务器为默认虚拟网络交换机分配静态IP地址?
默认情况下,libvirt会为需要它的每个虚拟网络交换机自动配置并启动dnsmasq dhcpd服务器的实例。
每个虚拟网络交换机都可以分配通过DHCP提供给来宾的IP地址范围。
默认的网络交换机使用dnsmasq服务器。

Libvirt使用一个程序,dnsmasq用于DNS,DHCP用于默认网络。

查看当前的dnsmasq DHCP配置

执行以下命令以列出网络

# virsh net-list

输出示例:

Name                 State      Autostart     Persistent
---------------------------------------------------------
default              active     yes           yes

要查看默认的网络信息,请执行:

# virsh net-dumpxml default

输出示例:

<network connections='2'>
  <name>default</name>
  <uuid>e346291e-f86b-4f2f-a16e-654136441805</uuid>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr0' stp='on' delay='0'/>
  <mac address='52:54:00:12:fe:35'/>
  <ip address='192.168.122.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.122.100' end='192.168.122.254'/>
    </dhcp>
  </ip>
</network>

DHCP范围在192.168.122.100和192.168.122.254之间。

如何在VM主机上配置静态来宾IP地址

首先找出您的访客虚拟机的MAC地址,执行:

# virsh dumpxml {VM-NAME-HERE} | grep -i '<mac'
# virsh dumpxml xenial | grep -i '<mac'

输出示例:

<mac address='52:54:00:4c:40:1c'/>

请记下要分配静态IP地址的Xenial VM的MAC地址。

编辑默认网络

执行以下命令:

# virsh net-edit default

查找以下部分:

<dhcp>
      <range start='192.168.122.100' end='192.168.122.254'/>

在范围后追加静态IP,如下所示:

<host mac='52:54:00:4c:40:1c' name='xenial' ip='192.168.122.4'/>

其中:

  • mac = '52:54:00:4c:40:1c'VM的Mac地址
  • name ='xenial'虚拟机名称。
  • ip ='192.168.122.4'VM的静态IP。

这是我的完整文件,其中包含三个VM的三个静态DHCP条目:

<network>
  <name>default</name>
  <uuid>e346291e-f86b-4f2f-a16e-654136441805</uuid>
  <forward mode='nat'/>
  <bridge name='virbr0' stp='on' delay='0'/>
  <mac address='52:54:00:12:fe:35'/>
  <ip address='192.168.122.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.122.100' end='192.168.122.254'/>
      <host mac='52:54:00:a0:cc:19' name='centos7' ip='192.168.122.2'/>
      <host mac='52:54:00:f7:a1:c8' name='puffy' ip='192.168.122.3'/>
      <host mac='52:54:00:4c:40:1c' name='xenial' ip='192.168.122.4'/>
    </dhcp>
  </ip>
</network>

重新启动DHCP服务:

# virsh net-destroy default
# virsh net-start default

输出示例:

Network default destroyed
Network default started

如果您正在运行名为xenial shutdown的来宾/VM,则它:

# virsh shutdown xenial
# /etc/init.d/libvirt-bin restart
# virsh start xenial
# ping -a 192.168.122.4

输出示例:

PING 192.168.122.4 (192.168.122.4) 56(84) bytes of data.
64 bytes from 192.168.122.4: icmp_seq=1 ttl=64 time=0.518 ms
64 bytes from 192.168.122.4: icmp_seq=2 ttl=64 time=0.202 ms
64 bytes from 192.168.122.4: icmp_seq=3 ttl=64 time=0.327 ms
^C
--- 192.168.122.4 ping statistics --
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 0.202/0.349/0.518/0.129 ms

每次来宾或称为xenial的VM联机(或重新引导以进行内核更新)时,dnsmasq DHCP服务器将获得192.168.122.4作为静态IP地址。