说明:Centos 7 默认的防火墙是 firewall ,鉴于 iptables 使用的比较广,本文简要介绍在 CentOS7.0 系统下 iptables 服务的安装以及相关的使用方法。

禁用 firewall 开机启动

为了防止与 iptables 服务冲突,先禁用 firewall 开机启动:

  • 使用 systemctl status firewalld 查看服务状态,active/inactive表明服务是运行/关闭状态(如下图)


    1. systemctl status firewalld

云服务器 ECS Linux Centos 7 系统 下iptables 服务的使用概述_Linux

  • 如果服务是运行状态,先关闭 firewall  服务,命令如下:



    停止以后然后执行下面命令禁用


    1. systemctl disable firewalld

    2. systemctl stop firewalld

安装 iptables
yum install -y iptables-services

出现 complete! 表示安装成功。

云服务器 ECS Linux Centos 7 系统 下iptables 服务的使用概述_Linux_02

启动 iptables
systemctl start iptables

云服务器 ECS Linux Centos 7 系统 下iptables 服务的使用概述_Linux_03

查看 iptables 默认规则
iptables -L

云服务器 ECS Linux Centos 7 系统 下iptables 服务的使用概述_Linux_04

在默认规则下,INTPUT 链中 ACCEPT 来自任何主机的访问。 

需要对规则进行修改,步骤如下:

  • 如之前已经设置过规则策略的,将原有的 iptables 文件保存一份,,避免之前设置的策略丢失,命令如下;


     

    1. cp -a /etc/sysconfig/iptables /etc/sysconfig/iptables.bak

  • 清空服务器上所有的规则


    1. iptables -F

  • 设置 INPUT 方向所有的请求都拒绝,这条策略加上以后所有访问服务器的请求全都会被拒绝掉,如果是线上业务请勿直接操作,会导致业务直接中断:


    1. iptables -P INPUT DROP

  • 放行系统常用的端口,比如 80 和 22 端口,实际的业务使用端口可以根据自己的需求来加,更多的协议放行可以自行再研究:


    1. iptables -I INPUT -p tcp dport 80 -m state state NEW -j ACCEPT


    1. iptables -I INPUT -p tcp dport 22 -m state state NEW -j ACCEPT

  • 然后使用 iptables -L 查看一下添加的规则是否生效


    云服务器 ECS Linux Centos 7 系统 下iptables 服务的使用概述_Linux_05
     

    1. iptables -L

  • 保存添加的规则


     

    1. iptables-save > /etc/sysconfig/iptables

设置 iptables 开机启动
systemctl enable iptables.service

操作完成后,重启服务器进行配置验证:

systemctl reboot