1、新建規(guī)則文件
mkdir /etc/iptables
vim /etc/iptables/rules.v4
寫入內(nèi)容
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m multiport --dports 135,137,138,139,445,3389 -j REJECT
-A OUTPUT -p tcp -m multiport --sports 135,137,138,139,445,3389 -j REJECT
COMMIT
2、手動加載測試
iptables-restore < /etc/iptables/rules.v4
3、設置開機生效
由于銀河麒麟系統(tǒng)使用的網(wǎng)絡管理工具不是傳統(tǒng)的ifupdown,而是NetworkManager,導致/etc/network/if-pre-up.d/目錄下的腳本重啟不會被觸發(fā)執(zhí)行。需要用更可靠的systemd服務來實現(xiàn)開機自動加載 iptables 規(guī)則。
步驟 1:創(chuàng)建 systemd 服務文件
sudo vim /etc/systemd/system/iptables.service
[Unit]
# 服務描述
Description=Load iptables Rules Automatically
# 依賴網(wǎng)絡預啟動目標,確保在網(wǎng)絡啟動前加載規(guī)則
Wants=network-pre.target
Before=network-pre.target network.target
# 取消默認依賴,避免啟動順序問題
DefaultDependencies=no
[Service]
# 一次性執(zhí)行服務(執(zhí)行完即退出)
Type=oneshot
# 核心命令:加載iptables規(guī)則(使用/sbin/iptables-restore絕對路徑)
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4
# 如需加載IPv6規(guī)則,取消下面的注釋(同樣用絕對路徑)
# ExecStart=/sbin/ip6tables-restore /etc/iptables/rules.v6
# 即使執(zhí)行完,仍標記服務為活躍狀態(tài)
RemainAfterExit=yes
[Install]
# 綁定到多用戶運行級別(開機默認級別)
WantedBy=multi-user.target
步驟 2:重新加載 systemd 并啟用服務
# 重新加載systemd配置,識別新創(chuàng)建的服務
sudo systemctl daemon-reload
# 啟用服務(設置開機自啟)并立即啟動服務(加載規(guī)則)
sudo systemctl enable --now iptables.service
執(zhí)行以下命令檢查服務是否正常運行:
sudo systemctl status iptables.service
重啟系統(tǒng),然后執(zhí)行sudo iptables -L -n,驗證規(guī)則是否已經(jīng)自動加載。