温馨提示×

怎样用脚本管debian防火墙

小樊
41
2026-09-29 11:43:44
栏目: 智能运维

在 Debian 上“管防火墙”通常有三种层级,从简单到专业依次是:

  1. 直接用 iptables / nft 命令(脚本化)
  2. 用 ufw(Debian 推荐新手)
  3. 用 firewalld(服务器常用)

下面我按**“用脚本管理”**的角度,分别给你示例。


一、用 ufw(最简单,推荐)

1️⃣ 安装并启用

sudo apt update
sudo apt install ufw
sudo ufw enable

2️⃣ 用脚本管理防火墙规则

例如 firewall.sh:

#!/bin/bash

# 清空现有规则
ufw --force reset

# 默认策略
ufw default deny incoming
ufw default allow outgoing

# 允许 SSH(非常重要)
ufw allow 22/tcp

# 允许 Web
ufw allow 80/tcp
ufw allow 443/tcp

# 允许内网
ufw allow from 192.168.1.0/24

# 启用
ufw enable
chmod +x firewall.sh
sudo ./firewall.sh

✅ 适合:个人服务器、VPS、新手


二、用 iptables(最底层、最灵活)

1️⃣ 安装

sudo apt install iptables

2️⃣ 示例脚本(清规则 + 基础防护)

iptables.sh

#!/bin/bash

# 清空
iptables -F
iptables -X

# 默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 本地回环
iptables -A INPUT -i lo -j ACCEPT

# 已建立连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 防 SYN 攻击
iptables -A INPUT -p tcp --syn -m limit --limit 1/s -j ACCEPT
sudo ./iptables.sh

⚠️ Debian 11+ 实际用的是 nftables,iptables 是兼容层


三、用 nftables(Debian 官方推荐)

1️⃣ 安装

sudo apt install nftables
sudo systemctl enable nftables

2️⃣ 脚本示例

nft.sh

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0;

        # 允许回环
        iif lo accept

        # 已连接
        ct state established,related accept

        # SSH
        tcp dport 22 accept
        tcp dport 80 accept
        tcp dport 443 accept

        # 默认拒绝
        drop
    }

    chain forward {
        type filter hook forward priority 0;
        drop
    }

    chain output {
        type filter hook output priority 0;
        accept
    }
}
sudo nft -f nft.sh

✅ 适合:现代 Debian、长期维护


四、开机自动执行脚本

ufw

sudo systemctl enable ufw

nftables

sudo systemctl enable nftables

iptables(老方式)

iptables-save > /etc/iptables.rules

五、怎么选?

场景 推荐
新手 / VPS ✅ ufw
精细控制 ✅ nftables
老系统 / 兼容 iptables
集群 / 云 firewalld

如果你愿意,可以告诉我:

  • Debian 版本(10 / 11 / 12)
  • 是本机防火墙还是网关
  • 要不要防 brute force / DDoS

我可以直接给你一套可生产的脚本。

0 踩