如何在 shell 腳本中包含目錄中的所有檔案(在本例中為 /etc/init.d/iptables)

如何在 shell 腳本中包含目錄中的所有檔案(在本例中為 /etc/init.d/iptables)

/etc/init.d/iptables start|stop|restart在不同的 ubuntu 伺服器上有一個腳本(這是一個普通的 shell 腳本)

對於每個新服務,我必須編輯並插入一行來開啟連接埠。這導致 init.d 腳本在不同的機器上有許多不同的版本。

是否可以自動包含所有文件/etc/iptables/include.d/

目標是應該只有一行開始/etc/init.d/iptables 的功能如下

include /etc/iptables/include.d/*

在附加文件之後/etc/iptables/include.d/我只想說

/etc/init.d/iptables restart

編輯:正如 Saurabh 指出的那樣,當命令需要一定的順序時,這可能會導致問題。進階設定可以有不同的目錄,例如:

/etc/iptables/include01.d/
/etc/iptables/include02.d/
/etc/iptables/include03.d/

並像這樣包括它們:

    包括/etc/iptables/include01.d/*
    ....也許主文件中有些代碼...
    包括/etc/iptables/include02.d/*
    包括/etc/iptables/include03.d/*

答案1

將以下行新增至 init.d 腳本。

run-parts --report /etc/iptables/include.d

它將作為 shell 腳本運行目錄中的所有內容(需要可執行)。

如果您只想執行以 .port 結尾的文件,您可以使用類似以下內容的命令:

run-parts --regex '\.port$' /etc/iptables/include.d/

如果您想確保順序正確,您可以命名檔案:

10_web.port
20_ssh.port
etc..

答案2

for f in /etc/iptables/include.d/*
 . $f
done

注意點和 %f 之間的空格

Saurabh 是對的 - 這不需要按您的預期工作,但使用一些命名約定,例如 10-xxx、20-yyy 等,它可能是可以管理的。

答案3

您可以在 bash 中定義簡單的函數:

function include() {
    for FILE in $( find "$1" -type f -print | sort )
    do
        source $FILE
    done
}

進而:

include some_dir/*

甚至:

include some_dir/*.conf

答案4

我認為您不能在 iptables 配置中包含文件。這種選擇是有意義的,因為防火牆規則在很大程度上取決於它們的編寫順序。如果我們只在資料夾中包含文件,iptables 將不知道先放置哪些規則,然後放置哪些規則。

相關內容