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?

#!/bin/bash

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

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."
else
    echo "Houston, we have a problem."
fi

View the full question and answer on Server Fault.

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