温馨提示×

CentOS防火墙备份与恢复方法

小樊
34
2025-11-27 18:24:59
栏目: 智能运维

CentOS 防火墙备份与恢复方法

一、先确认防火墙类型

  • 检查是否为 firewalld:执行 firewall-cmd --state,返回 running/not running 表示正在使用 firewalld。
  • 检查是否为 iptables:执行 systemctl status iptablesiptables -L -n -v,若服务存在且规则可见,多为 iptables 管理。
  • 注意:CentOS 7 及以后默认使用 firewalld;若系统同时安装了两套管理工具,恢复前务必确认当前在用哪一套,避免互相覆盖。

二、firewalld 的备份与恢复

  • 备份
    • 将当前运行时配置落盘为永久配置:sudo firewall-cmd --runtime-to-permanent(确保本次会话的修改被持久化)。
    • 备份配置目录:sudo cp -r /etc/firewalld /etc/firewalld_backup_$(date +%F);或使用归档:sudo tar czvf /backup/firewalld_$(date +%F).tar.gz /etc/firewalld
  • 恢复
    • 目录方式:sudo rsync -a /etc/firewalld_backup_YYYY-MM-DD/firewalld /etc/(或先 tar xzvf 解压到根目录),随后 sudo systemctl restart firewalld
    • 仅恢复规则文本(高级):将导出的规则文件通过 sudo firewall-cmd --stdin < rules.txt 导入,再 sudo firewall-cmd --reload 使配置生效。
  • 验证
    • 查看状态:firewall-cmd --state;查看默认区域与服务:firewall-cmd --get-default-zonefirewall-cmd --list-services

三、iptables 的备份与恢复

  • 备份
    • 直接导出规则:sudo iptables-save > /backup/iptables_$(date +%F).rules
    • 若系统使用传统的 iptables 服务,可用:sudo service iptables save(默认写入 /etc/sysconfig/iptables)。
  • 恢复
    • 从备份文件恢复:sudo iptables-restore < /backup/iptables_YYYY-MM-DD.rules
    • 若采用保存文件方式:sudo cp /backup/iptables_YYYY-MM-DD.rules /etc/sysconfig/iptables && sudo systemctl restart iptables
  • 验证
    • 查看规则:sudo iptables -L -n -v

四、注意事项与最佳实践

  • 变更前先备份,变更后在维护时间窗口内执行重载或重启,避免业务中断。
  • 区分 运行时永久 配置:firewalld 中未加 --permanent 的规则重启后会丢失,恢复后请执行 firewall-cmd --runtime-to-permanentfirewall-cmd --reload
  • 避免两套防火墙并存冲突:确认当前管理工具,必要时停用另一套(如 systemctl disable --now iptablessystemctl disable --now firewalld),再恢复对应配置。
  • 远程操作有断连风险:建议通过带外管理或至少保留一条当前会话,确保规则异常时能回滚;恢复后逐项校验关键端口与服务连通性。

0