kvm+nat+iptables

使用kvm虚拟化后,如果我们虚拟机使用的是nat模式,那么我们的虚拟机是可以访问外网,但是呢?外网无
法直接访问到我们内网虚拟机,这种情况下,我们就得在宿主机器里面做端口映射,允许外面访问我们虚拟
机的20、21、22、80、1433、3306、3389,还有ftp的被动端口;在linux下我们使用iptables来达到目的.
废话少说,来个实战!

准备描述:
宿主系统:ubuntu 12.10
宿主双公网IP: 192.168.0.100,10.0.1.100(这里我假设的啊,大家根据自己的实际情况修改)
双IP配置的接口分别是eth0、eth0:0

虚拟机机:
IP范围:192.168.10.2~192.168.10.62
虚拟机网关192.168.10.1

同时,我也对宿主稍微做了下IP 访问限制,和虚拟机vnc限制

现在我们开始附上我的脚本
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#!/bin/bash

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH

# define variable
DXIP="192.168.0.100"
WTIP="10.0.1.100"
IF0="eth0"
IF1="eth0:0"
INNET="192.168.10.0/24"
INIP="192.168.10."
PASVPORTSTART=49999
ENDIP=62
VPNIP1=100.100.100.2
VPNIP2=200.200.200.2
VPNIP3=1.1.1.2

# clear iptables rules
for tb in filter nat mangle
do
iptables -t $tb -F
iptables -t $tb -X
iptables -t $tb -Z
done

# policy set  and lo set
iptables -P INPUT DROP
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# allow  ip forward
sed -i "s/\#net\.ipv4\.ip_forward=1/net\.ipv4\.ip_forward=1/g" /etc/sysctl.conf
echo "1" > /proc/sys/net/ipv4/ip_forward

# allow who can use these port on this host and icmp
for ip in $VPNIP1 $VPNIP2 $VPNIP3
do
iptables -A INPUT -s $ip -p icmp -j ACCEPT
iptables -A INPUT -s $ip -p tcp --dport  22 -j ACCEPT
iptables -A INPUT -s $ip -p tcp --dport  5900:5990 -j ACCEPT
done

# kvm_servcie port
iptables -A INPUT -p tcp --dport  50120 -j ACCEPT

# data segment out wrap 、MASQUERADE
iptables -t nat -A POSTROUTING -s $INNET -o $IF0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s $INNET -o $IF1 -j MASQUERADE

# vm 3389、22、20、21、1433、3306、80 port and ftp pasv ports range
for i in `seq 2 $ENDIP`
do
[ "$i" == "26" ] && continue

for j in 20 21 22 80 1433 3306 3389
do
DPORT=$((1000*$i+$j))
iptables -t nat -A PREROUTING -i $IF0 -p tcp -m tcp --dport $DPORT \
                -j DNAT --to-destination ${INIP}$i:$j
iptables -t nat -A PREROUTING -i $IF1 -p tcp -m tcp --dport $DPORT \
                -j DNAT --to-destination ${INIP}$i:$j
done

for((p=1;p<=5;p++))
do
PASVPORT=$((PASVPORTSTART=$PASVPORTSTART+1))
iptables -t nat -A PREROUTING -i $IF0 -p tcp -m tcp --dport $PASVPORT \
                -j DNAT --to-destination ${INIP}$i:$PASVPORT
iptables -t nat -A PREROUTING -i $IF1 -p tcp -m tcp --dport $PASVPORT \
                -j DNAT --to-destination ${INIP}$i:$PASVPORT
done
done



猜你喜欢

转载自regjtc.iteye.com/blog/1828528