检查iptables是否运行的脚本不起作用

我有以下简单的脚本来检查iptables是否正在运行。 为什么总是返回“OK”,无论状态如何?

#!/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 

iptables的初始化脚本将永远不会完全返回该string; 它总是会有其他的东西,也有失败的条件,根本不匹配那个string。

相反,您应该检查脚本中的退出代码,因为它(在EL和Fedora上)在防火墙未激活时返回非零值,如果它处于活动状态,则返回零。

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

您将$SERV设置$SERV等于文本string值“ /sbin/service iptables status ”,您需要执行该命令并存储结果 。 您可以通过回显$SERV来validation。 正如所写的,它总是会评估为不平等。

SERV=$(/sbin/service iptables status)

另外,确保输出符合预期。 我的版本返回iptables: Firewall is not running. (你当然可能会有所不同。)

在“ 高级Bash脚本指南”中阅读有关子壳体的更多信息。

脚本正在做它说的。 请记住,[“$ SERV”=“$ EXPR”]是比较string ,它们是不相等的。

所以,testing的退出状态总是非零的,所以总是去“其他”。

你需要的是使用Command Subtitution ,而不是使用SERV ='/ sbin / service iptables status'

 SERV="$(/sbin/service iptables status)" 

要么

 SERV=`/sbin/service iptables status` 

HTH