手把手教您把CentOS7服务器变成上网路由器(基于iptables)

转自: http://www.jianshu.com/p/f198c1a2e9ac

网络拓扑图及说明

说明

1 服务器通过静态IP上网,外网连接eth0口,IP为200.0.0.2;eth1口连接内网交换机,内网网段为192.168.10.1/24。
2 内网中的所有机器通过NAT上网,也要通过DHCP服务器自动获得IP地址。其中192.168.10.254为一台FTP服务器,需要对外提供FTP服务。
3 服务器本身不对外提供任何服务,仅对内网提供DHCP服务以及SSH管理。
4 内网机器使用运营商的DNS。

配置步骤

(系统IP配置方法这里不再赘述)

关闭系统自带的防火墙
停止firewalld服务
1
systemctl stop firewalld
禁止firewalld服务自启动
1
systemctl disable firewalld
安装iptables防火墙和DHCP服务器
安装iptables服务
1
yum -y install iptables-services
安装dhcp服务
1
yum -y install dhcp
对iptables进行初始化工作
清空filter表
1
iptables -F
清空nat表
1
iptables -t nat -F
默认禁止所有传入连接
1
iptables -P INPUT DROP
默认允许所有传出连接
1
iptables -P OUTPUT ACCEPT
默认禁止路由转发
1
iptables -P FORWARD DROP
打开系统的IP转发功能
1
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
不用重启,立即生效
1
sysctl -p
按以下模版配置DHCP服务器

配置文件位置:/etc/dhcp/dhcpd.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#为 192.168.10.0/24 提供DHCP服务
subnet 192.168.10.0 netmask 255.255.255.0 {
range 192.168.10.2 192.168.10.253; #地址池范围
option broadcast-address 192.168.10.255; #广播地址
option routers 192.168.10.1; #默认网关
option domain-name-servers 202.96.134.33, 202.96.128.22; #运营商DNS服务器
option netbios-name-servers 192.168.10.1; #WINS服务器
option domain-name lan; #搜索域
default-lease-time 86400; #默认租约时间,单位为秒
max-lease-time 86400; #最长租约时间,单位为秒
}
#FTP服务器设置静态IP绑定
host ftp_server {
hardware ethernet 12:34:56:11:11:11; #FTP服务器的MAC地址
fixed-address 192.168.10.254; #绑定的IP地址
}

配置iptables的传入连接
允许环回接口的传入连接
1
iptables -A INPUT -i lo -j ACCEPT
允许已建立的传入连接
1
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
允许DHCP传入连接
1
iptables -A INPUT -i eth1 -p udp --dport 67:68 -j ACCEPT
允许SSH传入连接
1
iptables -A INPUT -i eth1 -p tcp --dport 22 -j ACCEPT
配置iptables的NAT转发(重点)
允许来自内网的传出连接
1
iptables -A FORWARD -s 192.168.10.0/24 -j ACCEPT
开启源NAT功能

即将来自内网主机的IP转换为外网IP。

1
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j SNAT --to 200.0.0.2

配置端口映射
1
iptables -t nat -A PREROUTING -d 200.0.0.2 -p tcp --dport 21 -j DNAT --to 192.168.10.254
允许到FTP服务器的传入连接
1
iptables -A FORWARD -d 192.168.10.254 -p tcp --dport 21 -j ACCEPT
保存iptables配置
1
iptables-save > /etc/sysconfig/iptables
启动iptables和dhcp服务
启动iptables
1
systemctl start iptables
开机自动启动iptables
1
systemctl enable iptables
启动dhcpd
1
systemctl start dhcpd
开机自动启动dhcpd
1
systemctl enable dhcpd
配置完成!