我寫了一個shell腳本來讀取一個由IP地址組成的文件,然後在iptables的幫助下將它們封鎖。它工作正常,但是當我第二次運行腳本時,它再次寫入規則(重複)。我想要檢查IP是否已經被阻塞,然後忽略阻塞。這裏是腳本:第一次腳本運行後Shell腳本來讀取文件
#!/bin/bash
ipadds="/home/asad/Downloads/blacklist"
dropit=$(grep -Ev "^#" $ipadds)
for i in $dropit; do
iptables -A INPUT -s $i -j DROP
iptables -A FORWARD -s $i -j DROP
done
輸出:第2次腳本運行後
[email protected]:/home/asad/Downloads# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
Chain FORWARD (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
輸出:
[email protected]:/home/asad/Downloads# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
Chain FORWARD (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
DROP all -- 192.168.248.2 anywhere
DROP all -- 192.168.232.20 anywhere
DROP all -- 192.168.232.5 anywhere
DROP all -- 192.168.232.190 anywhere
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
如何避免這種重複?任何幫助,請
不要使用'for'用於循環命令的輸出,使用過程中,替代與'while' – Inian
@gniourf_gniourf:意識到這只是它並沒有解決問題。 – Inian
您的預期代碼不適用於此方式。您應該需要一個數組來存儲命令輸出。您當前的語法允許shell執行單詞拆分以將單個空格分隔的行處理爲多個條目 – Inian