Linux

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > Linux > linux防火墙iptables做隔离端口脚本

linux如何通过防火墙iptables做隔离端口的脚本

作者:数据湖填坑

这篇文章主要介绍了linux如何通过防火墙iptables做隔离端口的脚本问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

通过防火墙iptables做隔离端口的脚本

vi iptables_fix.sh
#!/bin/bash
#备份旧的规则
iptables-save > “/opt/firewall-“date "+%Y-%m-%d-%H:%M:%S"”.txt”

获取集群内hosts的ip,空格分隔

clusters=cat /etc/hosts | grep -v ::1 | grep -v "^$" | awk '{print $1}'

配置集群外的ip,空格分隔,格式如下

business=“127.0.0.1 172.17.0.1/16”

配置需要隔离的端口,空格分隔,以22为例

block_ports=“22”
echo “FireWall fix…”

新建chain

iptables -t filter -N BIGDATA_BLOCK_PORTS

添加集群内ip白名单

for block_port in $block_ports;
do
for chost in $clusters;
do
#echo $ahost
iptables -I BIGDATA_BLOCK_PORTS -s $chost -p tcp --dport $block_port -j ACCEPT
iptables -I BIGDATA_BLOCK_PORTS -s $chost -p udp --dport $block_port -j ACCEPT
done
done

添加集群外ip白名单

for block_port in $block_ports;
do
for bhost in $business;
do
#echo $ahost
iptables -I BIGDATA_BLOCK_PORTS -s $bhost -p tcp --dport $block_port -j ACCEPT
iptables -I BIGDATA_BLOCK_PORTS -s $bhost -p udp --dport $block_port -j ACCEPT
done
done

最后隔离端口

for block_port in $block_ports;
do
iptables -A BIGDATA_BLOCK_PORTS -p tcp --dport $block_port -j DROP
iptables -A BIGDATA_BLOCK_PORTS -p udp --dport $block_port -j DROP
done
将BIGDATA_BLOCK_PORTS加入INPUT和FORWARD
iptables -I INPUT -j BIGDATA_BLOCK_PORTS
iptables -I FORWARD -j BIGDATA_BLOCK_PORTS
echo "fix finished

同时开启firewall和iptables

使用向导

With the iptables service, every single change means flushing all the old rules and reading all the new rules from /etc/sysconfig/iptables, while with firewalld there is no recreating of all the rules. Only the differences are applied. Consequently, firewalld can change the settings during runtime without existing connections being lost.

翻译

firewalld与iptables(和ip6tables)服务的本质区别是:

iptables服务将配置存储在/etc/sysconfig/iptables和/etc/sysconfig/ip6tables中,而firewalld将配置存储在/usr/lib/firewalld/和/etc/firewalld/中的各种XML文件中。

注意,/etc/sysconfig/iptables文件不存在,因为在Red Hat Enterprise Linux上默认安装了firewalld。

在iptables服务中,每次更改都意味着刷新所有旧规则并从/etc/sysconfig/iptables读取所有新规则,而在firewalld中不需要重新创建所有规则。

只应用差异。因此,firewalld可以在运行时更改设置,而不会丢失现有的连接。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文