防火墙端口管理

​ 防火墙端口管理在操作中经常会用到,但是在实际布置生产环境或者一些带单向网闸一系列设备时,我们需要关闭的端口就会很多,这时再去一个个关闭,很显然就非常麻烦了,所以运维经常使用自动化脚本去进行管理。

以下脚本可直接使用(不能运行时,请修改对应的系统指令)

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
32
33
34
35
36
37
38
39
40
41
#!/bin/bash


# 获取用户输入的要关闭的端口列表
echo "指定区间格式为: 1000:2000 ===> 将丢弃1000到2000所有端口的tcp数据包"
echo "请输入要关闭的端口列表,用空格分隔:"
read -a ports_to_close

# 获取用户输入的要允许的端口列表
echo "指定区间格式为: 1000:2000 ===> 将允许1000到2000所有端口的tcp数据包"
echo "请输入要允许的端口列表,用空格分隔:"
read -a ports_to_allow

# 备份iptables配置
iptables-save > /path/to/iptables_backup.txt

# 加载iptables规则
iptables -F
iptables -X
iptables -Z

# 允许流量通过的端口
for port in "${ports_to_allow[@]}"; do
iptables -A INPUT -p tcp --dport $port -j ACCEPT
iptables -A OUTPUT -p tcp --sport $port -j ACCEPT
done

# 关闭的端口
for port in "${ports_to_close[@]}"; do
iptables -A INPUT -p tcp --dport $port -j DROP
iptables -A OUTPUT -p tcp --sport $port -j DROP
done

# 保存iptables规则(redhat系统)
service iptables save
# 或 iptables-save > /etc/sysconfig/iptables

# (debian系统)
# sudo sh -c "iptables-save > /etc/iptables/rules.v4"

echo "防火墙端口已更新。"

防火墙端口管理
https://bote798.top/2025/01/06/防火墙端口管理/
作者
bote798
发布于
2025年1月6日
许可协议