监控firewalld需三步:1.用systemctl status和firewall-cmd --state每1–2分钟检查服务是否active(running);2.连续3次失败即告警;3.定期校验关键端口(如22、80)及规则数量是否符合预期。

新手配置Linux防火墙状态监控告警,关键不是堆工具,而是理清“谁在管防火墙、它是否活着、异常时怎么知道”这三件事。firewalld 是 CentOS/RHEL 7+ 和多数现代发行版默认的防火墙管理器,它的运行状态本身就是一个核心健康指标——服务宕了,规则再全也形同虚设。
确认 firewalld 服务是否稳定运行
这是监控的第一步,也是最基础的健康检查。
- 用 systemctl status firewalld 查看当前状态:显示 active (running) 才算正常;若为 inactive (dead) 或 failed,说明服务已退出或启动失败
- 用 firewall-cmd --state 做轻量级探测:返回 running 表示守护进程响应正常;返回 not running 则需立即排查
- 别只看一次:监控脚本或采集器应每1–2分钟执行一次上述命令,并记录结果。连续3次失败即触发告警
监控防火墙规则是否被意外清空或重载失败
服务在跑,不代表策略有效。有人误执行 firewall-cmd --reload 后忘记加 --permanent,或手动删了 /etc/firewalld/zones/public.xml,都会导致规则丢失。
- 定期比对关键端口:比如你明确需要开放 22(SSH)、80(HTTP),就用 firewall-cmd --zone=public --list-ports 检查它们是否仍在列表中
- 校验规则完整性:可简单统计开放端口数(
firewall-cmd --list-ports | wc -w)或服务数(firewall-cmd --list-services | wc -w),设定合理阈值(如端口数 - 关注 reload 操作日志:firewalld 会把重载记录写入
/var/log/firewalld,可用journalctl -u firewalld --since "1 hour ago" | grep reload追踪最近变更
用轻量脚本实现基础告警(无需 Prometheus)
新手不必一上来就搭整套监控栈。一个5行 shell 脚本 + 系统定时任务,就能守住底线。
- 写一个
/usr/local/bin/check-firewalld.sh:
if ! systemctl is-active --quiet firewalld; then
echo "ALERT: firewalld service is NOT running" | mail -s "? Firewalld Down" admin@example.com
elif [ $(firewall-cmd --list-ports | wc -w) -lt 2 ]; then
echo "ALERT: too few ports open in public zone" | mail -s "⚠️ Firewalld Rule Anomaly" admin@example.com
fi
- 给脚本加执行权限:chmod +x /usr/local/bin/check-firewalld.sh
- 加入 crontab 每5分钟跑一次:*/5 * * * * /usr/local/bin/check-firewalld.sh
- 邮件发送依赖本地
mailutils或ssmtp,Ubuntu/Debian 运行sudo apt install mailutils即可;CentOS 用yum install mailx
进阶提示:何时该上 Prometheus+Alertmanager
当你的服务器数量超过3台,或需要和 CPU、网络、应用端口等指标联动分析时,就该升级了。
- Node Exporter 默认不暴露 firewalld 状态,但你可以用 textfile collector 方式:让上面的检查脚本把结果写成
/var/lib/node_exporter/textfile/firewalld.prom,内容如:
firewalld_up 0
firewalld_open_ports_count 0
Node Exporter 会自动加载这个文件作为指标 - 在 Prometheus 中写告警规则:
groups:
- name: firewall-alerts
rules:
- alert: FirewalldDown
expr: firewalld_up == 0
for: 2m
labels:
severity: critical
annotations:
summary: "firewalld service is down on {{ $labels.instance }}"











