这段 Bash 脚本旨在自动化管理 Linux 系统中的 iptables 防火墙规则,并提供一个简单的交互式菜单来配置和查看开放端口。以下是脚本的主要功能和流程:
-
检查并安装所需包: 脚本首先检查系统类型是基于 RedHat 的(如 CentOS)还是基于 Debian 的(如 Ubuntu)。根据系统类型,它会使用相应的包管理器(
yum或apt)来更新系统并安装iptables和nmap。 -
清除重复规则: 在配置新的防火墙规则之前,脚本会清除现有的
iptables规则,以确保没有冲突或重复的规则存在。 -
配置所有端口的默认规则: 脚本将默认的
INPUT和FORWARD策略设置为DROP,OUTPUT策略设置为ACCEPT,并允许已建立和相关的连接。此步骤确保未明确允许的入站和转发流量被阻止。 -
查看所有开放端口: 提供一个功能来查看当前开放的输入和输出端口,便于管理员检查和验证防火墙配置。
-
管理端口: 脚本允许管理员打开或关闭指定端口。管理员可以输入端口号和相应的操作(打开或关闭),脚本将根据输入更新
iptables规则。 -
保存 iptables 规则: 脚本根据系统类型保存更新后的
iptables规则,以确保在系统重启后规则仍然有效。 -
主菜单: 脚本提供一个简单的交互式菜单,允许用户选择查看开放端口、管理现有端口或添加新端口。根据用户的选择,脚本会调用相应的功能执行操作。
这个脚本简化了 iptables 的配置过程,使系统管理员可以更方便地管理防火墙规则,从而提高系统的安全性和管理效率。通过自动化包安装、规则配置和保存,脚本减少了手动操作的错误风险,并提供了一个直观的用户界面来执行常见的防火墙管理任务。
#!/bin/bash
# 检查并安装所需包
install_packages() {
if [ -f /etc/redhat-release ]; then
sudo yum update -y
sudo yum install -y iptables nmap
elif [ -f /etc/lsb-release ]; then
sudo apt update
sudo apt install -y iptables nmap
else
echo "Unsupported OS. Please use CentOS or Ubuntu."
exit 1
fi
}
# 清除重复规则
clear_existing_rules() {
sudo iptables -F
sudo iptables -X
sudo iptables -Z
}
# 配置所有端口的默认规则
configure_default_rules() {
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
save_rules
}
# 查看所有开放端口
view_open_ports() {
echo "Currently open ports for INPUT:"
sudo iptables -L INPUT -v -n | grep dpt
echo "Currently open ports for OUTPUT:"
sudo iptables -L OUTPUT -v -n | grep dpt
}
# 管理端口
manage_port() {
local port=$1
local action=$2
if [ "$action" -eq 1 ]; then
sudo iptables -A INPUT -p tcp --dport "$port" -j ACCEPT
echo "Port $port opened."
elif [ "$action" -eq 0 ]; then
sudo iptables -D INPUT -p tcp --dport "$port" -j ACCEPT
echo "Port $port closed."
else
echo "Invalid action. Use '0' to close or '1' to open."
fi
}
# 保存 iptables 规则
save_rules() {
if [ -f /etc/redhat-release ]; then
sudo service iptables save
elif [ -f /etc/lsb-release ]; then
sudo iptables-save | sudo tee /etc/iptables/rules.v4 > /dev/null
else
echo "Unsupported OS. Please use CentOS or Ubuntu."
exit 1
fi
echo "iptables rules updated and saved."
}
# 主菜单
main_menu() {
echo "Select an option:"
echo "1. View all open ports"
echo "2. Manage existing port (open/close)"
echo "3. Add a new port (open/close)"
read -p "Enter your choice (1/2/3): " choice
case $choice in
1)
view_open_ports
;;
2)
read -p "Enter the port number to manage: " port
read -p "Enter '0' to close the port or '1' to open the port: " action
manage_port $port $action
save_rules
;;
3)
read -p "Enter the new port number to manage: " new_port
read -p "Enter '0' to close the port or '1' to open the port: " new_action
manage_port $new_port $new_action
save_rules
;;
*)
echo "Invalid choice. Please select 1, 2, or 3."
;;
esac
}
# 检查是否需要安装包
if ! command -v iptables &> /dev/null || ! command -v nmap &> /dev/null; then
install_packages
fi
# 配置默认规则
configure_default_rules
# 显示主菜单
main_menu
154

被折叠的 条评论
为什么被折叠?



