首页主机资讯centos防火墙备份与恢复

centos防火墙备份与恢复

时间2025-12-04 02:39:04发布访客分类主机资讯浏览1011
导读:CentOS 防火墙备份与恢复 一、先确认防火墙类型 查看是否为 firewalld:执行 firewall-cmd --state,返回 running/not running 表示正在使用 firewalld。 查看是否为 iptab...

CentOS 防火墙备份与恢复

一、先确认防火墙类型

  • 查看是否为 firewalld:执行 firewall-cmd --state,返回 running/not running 表示正在使用 firewalld。
  • 查看是否为 iptables:执行 systemctl is-active iptables,返回 active/inactive 表示使用传统 iptables 服务。
  • 注意:CentOS 7 及以后默认使用 firewalld;若系统同时安装了 iptables 服务,二者规则可能并存,建议统一为一种管理方式后再做备份与恢复。

二、iptables 的备份与恢复

  • 备份为文件(推荐):iptables-save > /path/to/iptables-$(date +%F).rules
  • 从文件恢复:iptables-restore < /path/to/iptables-$(date +%F).rules
  • 保存到默认配置(便于开机恢复):service iptables save(规则将写入 /etc/sysconfig/iptables
  • 直接恢复默认配置文件:iptables-restore < /etc/sysconfig/iptables
  • 清空规则的安全做法:优先使用 service iptables stop 停止服务,避免仅 iptables -F 导致空规则风险
  • 同时备份 IPv6(如有):ip6tables-save > /path/to/ip6tables-$(date +%F).rules;恢复:ip6tables-restore < /path/to/ip6tables-$(date +%F).rules

三、firewalld 的备份与恢复

  • 运行时配置导出/导入(不改动配置文件):
    • 导出:firewall-cmd --runtime-to-permanent > /path/to/firewalld-$(date +%F).xml
    • 导入:firewall-cmd --permanent --direct --file=/path/to/firewalld-$(date +%F).xml
    • 使导入生效:firewall-cmd --reload
  • 直接备份/恢复配置文件(最稳妥,包含 zones、services 等):
    • 备份目录:/etc/firewalld/(核心文件如 firewalld.conf/etc/firewalld/zones/*.xml
    • 建议打包:tar czf firewalld-backup-$(date +%F).tgz /etc/firewalld/
    • 恢复:tar xzf firewalld-backup-$(date +%F).tgz -C /
    • 使配置生效:firewall-cmd --reload
  • 说明:修改 zone/service 的 XML 后需 firewall-cmd --reload 才会生效;firewalld 默认有 9 个 zone,默认 public

四、自动化与回滚建议

  • 定期备份脚本示例(含时间戳与两种防火墙):
    #!/usr/bin/env bash
    ts=$(date +%F-%H%M%S)
    mkdir -p /opt/fw-backup/$ts
    
    if firewall-cmd --state >
        /dev/null 2>
        &
        1;
         then
      firewall-cmd --runtime-to-permanent >
         /opt/fw-backup/$ts/firewalld-runtime.xml
      cp -a /etc/firewalld /opt/fw-backup/$ts/firewalld-conf
      echo "firewalld 已备份到 /opt/fw-backup/$ts"
    elif systemctl is-active iptables >
        /dev/null 2>
        &
        1;
         then
      iptables-save >
         /opt/fw-backup/$ts/iptables.rules
      ip6tables-save >
         /opt/fw-backup/$ts/ip6tables.rules 2>
        /dev/null
      echo "iptables 已备份到 /opt/fw-backup/$ts"
    else
      echo "未检测到正在运行的防火墙服务"
    fi
    
  • 回滚建议:优先使用“配置文件级”备份进行全量回滚(firewalld 用打包的 /etc/firewalld;iptables 用导出的规则文件),回滚后执行 firewall-cmd --reloadservice iptables restart 使配置生效。

五、注意事项

  • 变更前先备份,并在维护窗口操作;执行 reload/restart 可能导致现有连接短暂中断。
  • 区分“运行时规则”和“永久规则”:--permanent 写入配置,未 reload 前不会影响当前会话;导入/恢复后务必 firewall-cmd --reload
  • 避免混用管理工具:同一台机器上同时启用并维护 firewalldiptables 容易冲突,建议统一为一种方案后再备份与恢复。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: centos防火墙备份与恢复
本文地址: https://pptw.com/jishu/763093.html
centos防火墙更新后需重启吗 Node.js在CentOS上的性能调优策略

游客 回复需填写必要信息