写了一个shell脚本用于批量关闭开放的端口。
#!/bin/bash
# 1. 声明待释放的端口区间,取值由外部指定
# 2. 要求start_port<=end_port
# 3. 显示指定端口数据类型为整数型
declare -i start_port=$1
declare -i end_port=$2
# 如果有错,直接退出,避免while死循环
set +e
while ((${start_port}<=${end_port}))
do
# 获取某个端口的防火墙规则,只取结果集的第一行
rule=`ufw status numbered | grep ${start_port} | head -1`
if test -z "${rule}"
then
# 如果没有指定端口的防火墙,则检查下一个端口
let start_port++
else
echo "rule: ${rule}"
# 从规则中取出rule_number
rule_num=`echo ${rule} | cut -f 1 -d "]" | sed 's/\[//'`
# rule_num=`echo ${rule} | cut -f 2 -d " " | sed 's/\[//' | sed 's/\]//'`
# rule_num=`echo ${rule} | cut -f 1 -d " " | head -1 | sed 's/\[//' | sed 's/\]//'`
echo "rule_num: ${rule_num}"
# 删除ufw规则有两种方法
# > ufw delete ${rule_number}
# > ufw delete ${allow port_number}
# 如果使用第二种,提示"Could not delete non-existent rule"
# 使用`echo -e`完成自动交互
echo -e "y\n" | ufw delete ${rule_num}
echo "Delete rule: ${rule}"
echo
# break
fi
done
闲的蛋疼,让gpt写了一个,gpt牛逼
#!/bin/bash
# 设置待删除规则的起始和终止端口号
start_port=$1
end_port=$2
# 检查输入参数是否正确传递
if [ "$#" -ne 2 ] || ! [[ "$start_port" =~ ^[0-9]+$ ]] || ! [[ "$end_port" =~ ^[0-9]+$ ]]; then
echo "错误:请按照以下格式运行这个脚本:"
echo "./delete_rules.sh <起始端口> <结束端口>"
exit 1
fi
for (( port_number=start_port; port_number<=end_port; port_number++ ))
do
# 列出所有匹配给定端口号的防火墙规则
rules=$(sudo ufw status numbered | grep "allow $port_number")
# 对于每一个找到的规则,都先输出它的详细信息,然后再将其删除
if [ -n "${rules}" ]; then
while read line; do
rule_number=$(echo "$line" | cut -d "[" -f2 | cut -d "]" -f1)
echo "找到一条指向端口 ${port_number} 的规则 (编号为 ${rule_number})!"
sudo ufw delete "$rule_number"
echo "成功删除该规则!"
done <<< "$rules"
else
echo "没有在防火墙规则列表中找到针对端口 ${port_number} 的规则。"
fi
done
echo "所有指定的防火墙规则已被成功删除!"