KVM安装完成后,有两种网络配置连接模式 —— 一种是nat上网方式(virbr0网卡连接),一种是bridge(br0、br1等方式连接)方式。由于虚拟机安装后,一般我们都会配置一个连接virbr0的一个nat网卡用于共享上网,所以这里主要说下通过宿主机的iptables配置实现192.168.122.X网段的KVM虚拟机在配置完成后可以直接上网操作。
1、开启路由转发
打开/etc/sysctl.conf文件,找到ip_forward项,将其改为如下:
net.ipv4.ip_forward = 1
2、更改iptables配置如下:
[[email protected] qemu]# cat /etc/sysconfig/iptables *nat :PREROUTING ACCEPT [193:185421] :POSTROUTING ACCEPT [177:10242] :OUTPUT ACCEPT [4:320] -A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -p tcp -j MASQUERADE --to-ports 1024-65535 -A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -p udp -j MASQUERADE --to-ports 1024-65535 -A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -j MASQUERADE COMMIT # Completed on Tue Jul 9 11:23:56 2013 # Generated by iptables-save v1.4.7 on Tue Jul 9 11:23:56 2013 *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [549:80184] -A INPUT -i virbr0 -p udp -m udp --dport 53 -j ACCEPT -A INPUT -i virbr0 -p tcp -m tcp --dport 53 -j ACCEPT -A INPUT -i virbr0 -p udp -m udp --dport 67 -j ACCEPT -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -d 192.168.122.0/24 -i br1 -j ACCEPT -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED,ESTABLISHED -j ACCEPT -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT -A FORWARD -i virbr0 -o virbr0 -j ACCEPT -A FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable -A FORWARD -i virbr0 -j REJECT --reject-with icmp-port-unreachable -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT # Completed on Tue Jul 9 11:23:56 2013 # Generated by iptables-save v1.4.7 on Tue Jul 9 11:23:56 2013 *mangle :PREROUTING ACCEPT [56905:10171652] :INPUT ACCEPT [553:43971] :FORWARD ACCEPT [56352:10127681] :OUTPUT ACCEPT [549:80184] :POSTROUTING ACCEPT [56901:10207865] -A POSTROUTING -o virbr0 -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill COMMIT # Completed on Tue Jul 9 11:23:56 2013 # Generated by iptables-save v1.4.7 on Tue Jul 9 11:23:56 2013
更改完iptables的配置后,重启iptabls服务加载生效。
最后这里也顺带提下bridge桥接模式的配置,启用桥模式只需要在虚拟机的相应的xml文件中,将虚拟机对应的网卡配置更改为如下即可:
<interface type=‘bridge‘> <mac address=‘52:54:00:f9:bd:b8‘/> <source bridge=‘br0‘/>
其中br0为宿主主机物理网口(如eth0) bridge的接口。
如果不需要nat方式的virbr0网口,也可以通过下面的方式删除(不推荐删除):
# virsh net-destroy default # virsh net-undefine default # service libvirtd restart
各网络接口桥接对应关系也可以通过下面的命令查看:
[[email protected] qemu]# brctl show bridge name bridge id STP enabled interfaces br0 8000.c81f66bbe018 no em1 virbr0 8000.52540081c656 yes virbr0-nic vnet0 vnet1
时间: 2024-11-04 19:26:55