在 Debian 上“管防火墙”通常有三种层级,从简单到专业依次是:
下面我按**“用脚本管理”**的角度,分别给你示例。
sudo apt update
sudo apt install ufw
sudo ufw enable
例如 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、新手
sudo apt install iptables
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 是兼容层
sudo apt install nftables
sudo systemctl enable nftables
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、长期维护
sudo systemctl enable ufw
sudo systemctl enable nftables
iptables-save > /etc/iptables.rules
| 场景 | 推荐 |
|---|---|
| 新手 / VPS | ✅ ufw |
| 精细控制 | ✅ nftables |
| 老系统 / 兼容 | iptables |
| 集群 / 云 | firewalld |
如果你愿意,可以告诉我:
我可以直接给你一套可生产的脚本。