bash 检查 iptables 用户链是否存在的最佳方法。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10775863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:23:13  来源:igfitidea点击:

best way to check if a iptables userchain exist.

bashshelliptables

提问by nashr rafeeg

i am trying to programmatically create userchains and delete them in iptables. I was wondering what is the best way to check if a userchain exist and if it does not create it.

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

回答by camh

Use iptables(8)to list the chain, redirecting stdout/stderr to /dev/null, and check the exit code. If the chain exists, iptableswill exit true.

使用iptables(8)列出链,重定向标准输出/标准错误来/dev/null,并检查退出代码。如果链存在,iptables则退出真。

This shell function is from my iptables front-end script:

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

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

Note that I use the -noption so that iptables does not try to resolve IP addresses to hostnames. Without this, you'll find this function would be slow.

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

You can then use this function to conditionally create a chain:

然后你可以使用这个函数有条件地创建一个链:

chain_exists foo || create_chain foo ...

where create_chainis another function to create the chain. You could call iptablesdirectly, but the above naming makes it quite obvious what is going on.

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