8

我正在尝试以编程方式创建用户链并在 iptables 中删除它们。我想知道检查用户链是否存在以及是否不创建它的最佳方法是什么。

4

1 回答 1

17

用于iptables(8)列出链,将 stdout/stderr 重定向到/dev/null,并检查退出代码。如果链存在,iptables将退出true。

这个 shell 函数来自我的 iptables 前端脚本:

chain_exists()
{
    [ $# -lt 1 -o $# -gt 2 ] && { 
        echo "Usage: chain_exists <chain_name> [table]" >&2
        return 1
    }
    local chain_name="$1" ; shift
    [ $# -eq 1 ] && local table="--table $1"
    iptables $table -n --list "$chain_name" >/dev/null 2>&1
}

请注意,我使用该-n选项以便 iptables 不会尝试将 IP 地址解析为主机名。没有这个,你会发现这个函数会很慢。

然后,您可以使用此函数有条件地创建一个链:

chain_exists foo || create_chain foo ...

create_chain创建链的另一个函数在哪里。您可以iptables直接调用,但上面的命名使发生的事情变得非常明显。

于 2012-05-28T12:23:47.760 回答