Search code examples
bashiptablesfirewalld

detecting installer iptables and firewalld with if conditions / bash


Creating script to detect

  • installer (yum or apt-get)
  • iptables
  • firewalld

Current system:

  • Debian 8
  • iptables NOT installed
  • firewalld NOT installed

Theoretically it must be working, but missing something:

#!/bin/bash
installer_check () {
  if [[ $(apt-get -V >/dev/null 2>&1) -eq 0 ]]; then
    installer=apt
  elif [[ $(yum --version >/dev/null 2>&1) -eq 0 ]]; then
    installer=yum
  fi
}

frw_det_yum () {
  if [[ $(rpm -qa iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_y=installed_none
  elif [[ $(rpm -qa firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_y=installed_none
  fi
}

frw_det_apt () {
  if [[ $(dpkg -s iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_a=installed_none
  elif [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_a=installed_none
  fi
}

echo "checking installer"
installer_check
echo -e "$installer detected"

if [ "$installer" = "yum" ]; then
  echo "runing firewallcheck for yum"
  frw_det_yum
  echo $ipt_status
fi

if  [ "$installer" = "apt" ]; then
  echo "checking installer for apt"
  frw_det_apt
  echo $frd_status_a
fi

output I'm getting:

~# ./script
checking installer
apt detected
checking installer for apt

So in this current system I'm not getting any value for $frd_status_a


Solution

  • You expect the body of the following to be invoked if firewalld is not installed:

    if [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
      frd_status_a=installed_none
    fi
    

    However, let's look at what this actually does:

    • redirect stdout and stderr of the command dpkg -s firewalld to /dev/null
    • capture the stdout of that command, and compare it numerically to the value 0
    • If the stdout of that command (which has no stdout because you redirected it) has a numeric value other than 0, then we set the flag.

    Of course that flag will never be set, no matter what the dpkg command does when it's invoked, and no matter what its output is.


    Consider instead:

    if ! dpkg-query -l firewalld; then
      frd_status_a=installed_none
    fi