【问题标题】:best way to check if a iptables userchain exist.检查 iptables 用户链是否存在的最佳方法。
【发布时间】:2016-12-15 11:37:30
【问题描述】:

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

【问题讨论】:

    标签: bash shell iptables


    【解决方案1】:

    使用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,但是上面的命名很明显是怎么回事。

    【讨论】:

    • 应该是iptables(8)iptables -t $table ...
    • @mkj: iptables(8) - 我已经解决了这个问题,谢谢。 -t $table - 查看上面的行,您会看到 $table 已经包含 --table。我这样做是为了让$table 为空或“--table ”,因为该表是可选的,如果没有表参数,您不需要 -t/--table。
    猜你喜欢
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2018-12-26
    • 1970-01-01
    • 2011-05-25
    • 2012-08-29
    • 2011-03-20
    相关资源
    最近更新 更多