在 Linux 系統中,iptables 防火牆規則的異機備份與恢復是維運常見需求。本文以「主控機」(生產環境)與「備份機」(災備環境)為例,完整說明如何透過排程自動同步防火牆規則,並在故障時快速切換。
/etc/sysconfig/iptablesmkdir -p /bak/iptables/
mkdir /root/script/
/root/script/backup.sh:#!/bin/bash
cp /etc/sysconfig/iptables /bak/iptables/iptables_$(date +%Y%m%d%H)
*/10 * * * * /usr/sbin/ntpdate 210.72.145.44
10 * * * * sh /root/script/backup.sh
mkdir -p /bak/iptables/{lt,yd}
mkdir /root/script/
/root/script/scp_lt.sh:#!/usr/bin/expect -f
set password gst
spawn scp -P 22 root@202.105.135.52:/etc/sysconfig/iptables /bak/iptables/lt/iptables
set timeout 300
expect "root@202.105.135.52's password:"
send "$password\r"
set timeout 300
send "exit\r"
expect eof
/root/script/scp_yd.sh(IP 替換為 183.62.178.91)。/root/script/backup.sh,整合下載、IP 替換、套用規則:#!/bin/bash
expect /root/script/scp_lt.sh
expect /root/script/scp_yd.sh
# 將主控機 IP 替換為備份機對應 IP
sed -i 's/202.105.135.52/183.62.178.85/g' /bak/iptables/lt/iptables
sed -i 's/58.251.49.18/58.250.56.154/g' /bak/iptables/lt/iptables
# 套用規則並存檔
cp /bak/iptables/lt/iptables /etc/sysconfig/iptables
/etc/init.d/iptables restart
/etc/init.d/iptables save
# 歸檔備份
mv /bak/iptables/lt/iptables /bak/iptables/lt/iptables_$(date +%Y%m%d%H)
mv /bak/iptables/yd/iptables /bak/iptables/yd/iptables_$(date +%Y%m%d%H)
*/10 * * * * /usr/sbin/ntpdate 210.72.145.44
20 * * * * sh /root/script/backup.sh
除異機備份外,iptables 亦可直接開啟/關閉防火牆功能。生產環境建議搭配版本控制(如 Git)管理規則歷史,並定期演練恢復流程,確保災備有效性。