需求如下,kvm安装后默认的NAT是192.168.122.0 ,此时假如物理网卡为专线地址10.0.0.1,此时需要将192.168.122.0段的虚拟机的ssh端口映射到10.0.0.1的10022端口上,可以执行下面2条命令
firewall-cmd --add-port=10022/tcp
firewall-cmd --add-forward-port=port=10022:proto=tcp:toport=22:toaddr=192.168.122.x
但是,执行后会发现并没有生效,此时执行iptables -F 发现可以达到目的,但是会清理掉其他的iptables规则 。
通过多次排查后发现问题的症结是因为firewall-cmd 在每次重启firewalld服务或者执行firewall-cmd --reload后都会形成一系列规则,这其中的某一条规则阻止了映射行为
iptables -vnL FORWARD
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 ctstate RELATED,ESTABLISHED
0 0 ACCEPT all -- virbr0 * 192.168.122.0/24 0.0.0.0/0
0 0 ACCEPT all -- virbr0 virbr0 0.0.0.0/0 0.0.0.0/0
0 0 REJECT all -- * virbr0 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
0 0 REJECT all -- virbr0 * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
0 0 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
0 0 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
0 0 FORWARD_direct all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 FORWARD_IN_ZONES_SOURCE all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 FORWARD_IN_ZONES all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 FORWARD_OUT_ZONES_SOURCE all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 FORWARD_OUT_ZONES all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate INVALID
0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
就是这条规则导致外面的数据无法流转到br0网桥上
此时可以在他前面增加一条规则,去放行相应的流量
iptables -I FORWARD 4 -i eth0 -o virbr0 -p tcp --dport 22 -j ACCEPT。
然后会遇到下一个问题,如何保存iptables
iptables-save > /etc/sysconfig/iptables
然后写一个脚本 在每次重启后把iptables还原
脚本内容如下
#!/bin/bash
# Wait for firewalld service to be loaded
while ! systemctl is-active firewalld >/dev/null 2>&1; do
sleep 1
done
# Wait for additional time to ensure that the firewall has been initialized
sleep 10
# Restore iptables rules from file
/usr/sbin/iptables-restore < /etc/sysconfig/iptables
然后再rclocal文件中调用脚本即可
cat /etc/rc.d/rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
#touch /var/lock/subsys/local
#iptables-restore < /etc/sysconfig/iptables
/root/11.sh
记得要给rcloca赋予执行权限
chmod +x /etc/rc.d/rc.local
此时重启后NAT可实现
标签:iptables,映射,--,0.0,KVM,ACCEPT,NAT,FORWARD,virbr0 From: https://www.cnblogs.com/ruiruiblog/p/17484968.html