Script to check if iptables is running is not working

j5iApart2 asked:

I have the following simple script to check if iptables is running or not. Why does it always returns ‘OK’ no matter what the status is?


SERV='/sbin/service iptables status'
EXPR='Firewall is stopped.'
        if [ "$SERV" = "$EXPR" ]
                        echo 'Firewall is not Running'
                        exit 2
                        echo 'OK'
                        exit 0

My answer:

The init script for iptables will never return exactly that string; it will always have something else in it, and there are also failure conditions which don’t match that string at all.

Instead, you should check the exit code from the script, as it (on EL and Fedora) returns non-zero if the firewall is not active and zero if it is active.

/sbin/service iptables status >/dev/null 2>&1
if [ $? = 0 ]; then
    echo "All systems go."
    echo "Houston, we have a problem."

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.