サーバー完成図書を自動で作りたいんだ 第7話 iptablesで開放されているポート

#!/bin/sh
IFS=$'\n'
SCRIPT_PATH=`echo $(cd $(dirname $0);pwd)`
TMPFILE=${SCRIPT_PATH}/iptables.tmp

DIR="Inbound"
PROTO=""
IP=""
PORT=""

function flush_line(){
  PROTO=""
  IP=""
  PORT=""
  ALL_RANGES=true
}

iptables -nvxL | sed -e "s/state NEW//g" | grep -v state | sed -e "s/^[0-9 ]\+//g" | grep -v " lo " | sed -e "s/spt:[^ ]\+//g" | sed -e "s/[ \t]\+/ /g" 1> ${TMPFILE}
if [ `cat ${TMPFILE} | grep ACCEPT | wc -l` -gt 0 ]; then
echo "|_. 方向|_. プロトコル|_. ポート|_. IPアドレス|"
for LINE in `cat ${TMPFILE}`
do
  LINE=`echo ${LINE} | sed -e "s/[ \t]\+/ /g"`
  if [[ "${LINE}" =~ ^(Chain OUTPUT) ]]; then
    flush_line;
    DIR="Outbound"
  elif [[ "${LINE}" =~ ^ACCEPT ]]; then
    flush_line;
    PORT=`echo ${LINE} | cut -f9 -d' ' | cut -f2 -d:`
    if [ ! -n "${PORT}" ]; then
      PORT="All"
    fi
    PROTO=`echo ${LINE} | cut -f2 -d' '`
    if [ ! -n "${PROTO}" ] || [ "${PROTO}" == "all" ] ; then
      PROTO="All"
    fi
    if [ "${DIR}" == "Inbound" ]; then
      IP=`echo ${LINE} | cut -f6 -d' '`
    else
      IP=`echo ${LINE} | cut -f7 -d' '`
    fi
    echo "|${DIR}|${PROTO}|${PORT}|${IP}|"
  fi
flush_line;
done
fi