kvm网络隔离禁止虚拟机之间通信

nwfilter xml文件默认路径: /etc/libvirt/nwfilter/

cat deny-test.xml
<filter name='deny-test' chain='ipv4' priority='-700'>
  <uuid>fce8ae34-e69e-83bf-262e-30786c1f8079</uuid>
  <rule action='drop' direction='out' priority='200'>
    <ip srcipaddr='172.21.13.102' dstipaddr='172.21.13.107' dstipmask='32'/>
  </rule>
</filter>


virsh nwfilter-define deny-test.xml
virsh nwfilter-list #确认是否添加成功


virsh edit xxx

<interface type='bridge'>
      <mac address='52:54:00:7c:17:86'/>
      <source bridge='br0'/>
      <model type='virtio'/>
      <filterref filter='deny-test'/> #add
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>

重启虚拟机

宿主机上执行:

ebtables -t nat -L


确认规则有没有添加成功

Bridge table: nat

Bridge chain: PREROUTING, entries: 1, policy: ACCEPT
-i vnet46 -j libvirt-I-vnet46

Bridge chain: OUTPUT, entries: 0, policy: ACCEPT

Bridge chain: POSTROUTING, entries: 0, policy: ACCEPT

Bridge chain: libvirt-I-vnet46, entries: 1, policy: ACCEPT
-p IPv4 -j I-vnet46-ipv4

Bridge chain: I-vnet46-ipv4, entries: 1, policy: ACCEPT
-p IPv4 --ip-src 172.21.13.102 --ip-dst 172.21.13.107 -j DROP 

简单 SHELL 

#!/bin/bash
# usage ./1.sh 172.21.13.102 deny-test 
tmpxml=$(mktemp /tmp/ifcfg.XXX)
macaddr="$(virsh domiflist $1 | awk "/bridge\s/ {print \$NF}")"
if [ -z "$macaddr" ]; then 
    echo "vm not exist" 
    exit 2
fi
if [ -z "$2" ]; then 
    echo "nwfilter name is null" 
    exit 2
fi

cat > "$tmpxml" <<EOF
<interface type='bridge'>
    <mac address='$macaddr'/>
    <source bridge='br0'/>
    <model type='virtio'/>
    <filterref filter='$2'/>
    <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>
EOF
virsh update-device "$1" "$tmpxml" --live --persistent --config
rm "$tmpxml"

发表评论

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