CentOS 防火墙备份与恢复方法
一、先确认防火墙类型
firewall-cmd --state,返回 running/not running 表示正在使用 firewalld。systemctl status iptables 或 iptables -L -n -v,若服务存在且规则可见,多为 iptables 管理。二、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-zone、firewall-cmd --list-services。三、iptables 的备份与恢复
sudo iptables-save > /backup/iptables_$(date +%F).rules。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。四、注意事项与最佳实践
--permanent 的规则重启后会丢失,恢复后请执行 firewall-cmd --runtime-to-permanent 并 firewall-cmd --reload。systemctl disable --now iptables 或 systemctl disable --now firewalld),再恢复对应配置。