在 CentOS 7.3 上安装并启用 iptables 记录规则的步骤如下:
1. 停止并禁用 firewalld(若已启用)CentOS 7 默认使用 firewalld,需先停止并禁用它以避免冲突:
systemctl stop firewalld.servicesystemctl disable firewalld.service2. 安装 iptables 相关服务CentOS 7 默认不包含 iptables.service,需手动安装:
yum -y install iptables-services iptables3. 验证安装状态检查服务是否安装成功并启动:
systemctl status iptables.service- 启动服务:systemctl start iptables.service
- 设置开机自启:systemctl enable iptables.service
4. 清空现有策略(可选)若需从头配置规则,可清空现有策略:
iptables -F # 清空所有规则iptables -X # 删除自定义链iptables -Z # 计数器归零5. 配置 iptables 规则基础规则示例- 允许特定 IP 访问端口(如允许 10.10.11.11 访问 9200 端口):iptables -I INPUT -s 10.10.11.11 -p tcp --dport 9200 -j ACCEPT
- 拦截所有 IP 访问端口(如拦截所有 IP 访问 9200 端口):iptables -A INPUT -p tcp --dport 9200 -j DROP
- 允许 IP 段访问端口(如允许 10.10.23.11-10.10.23.15 访问 9200 端口):iptables -I INPUT -m iprange --src-range 10.10.23.11-10.10.23.15 -p tcp --dport 9200 -j ACCEPT
记录日志规则若需记录被拦截的流量(如记录所有被 DROP 的数据包):
- 创建自定义链(用于日志记录):iptables -N LOG_DROP
- 添加日志规则(将匹配的数据包发送到 LOG_DROP 链):iptables -A INPUT -j LOG_DROP
- 在 LOG_DROP 链中记录日志并丢弃数据包:iptables -A LOG_DROP -j LOG --log-prefix "IPT_DROP: " --log-level 6iptables -A LOG_DROP -j DROP
--log-prefix:日志前缀,便于过滤。
--log-level 6:日志级别(6 为 info)。
6. 查看当前规则iptables -nL --line-number7. 保存规则必须保存规则,否则重启后失效:
service iptables save或使用:
/usr/libexec/iptables/iptables.init save8. 重启服务使规则生效systemctl restart iptables.service关键注意事项- 规则顺序:iptables 按顺序匹配规则,先匹配的规则优先生效。需将具体规则(如允许特定 IP)放在通用规则(如拦截所有)之前。
- 日志路径:日志默认记录到 /var/log/messages,可通过 rsyslog 配置单独文件(如 /var/log/iptables.log)。
- 测试规则:配置后使用 telnet 或 curl 测试端口连通性,确保规则按预期工作。
完整示例流程# 1. 停止 firewalldsystemctl stop firewalldsystemctl disable firewalld# 2. 安装 iptablesyum install -y iptables-services iptables# 3. 启动并设置开机自启systemctl start iptablessystemctl enable iptables# 4. 清空旧规则(可选)iptables -Fiptables -Xiptables -Z# 5. 添加规则(允许 10.10.11.11 访问 9200,拦截其他所有)iptables -I INPUT -s 10.10.11.11 -p tcp --dport 9200 -j ACCEPTiptables -A INPUT -p tcp --dport 9200 -j DROP# 6. 添加日志规则(记录被拦截的流量)iptables -N LOG_DROPiptables -A INPUT -j LOG_DROPiptables -A LOG_DROP -j LOG --log-prefix "IPT_DROP: " --log-level 6iptables -A LOG_DROP -j DROP# 7. 保存并重启service iptables savesystemctl restart iptables通过以上步骤,您可在 CentOS 7.3 上成功安装并配置 iptables,同时记录关键流量日志。