Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to check if a iptables userchain exist.

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

like image 564
nashr rafeeg Avatar asked May 27 '12 17:05

nashr rafeeg


1 Answers

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

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

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
}

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

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

chain_exists foo || create_chain foo ...

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

like image 135
camh Avatar answered Oct 19 '22 21:10

camh