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

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

DIR=""
PROTO=""
IP=""
PORT=""
ALL_RANGES=true

function flush_line(){
  if [ -n "${DIR}" ] && [ ${ALL_RANGES} == true ]; then
    echo "|${DIR}|${PROTO}|${PORT}|All|"
  fi
  DIR=""
  PROTO=""
  IP=""
  PORT=""
  ALL_RANGES=true
}

sh ${SCRIPT_PATH}/desc_securitygroups.sh 1> ${TMPFILE}
if [ `cat ${TMPFILE} | wc -l` -gt 0 ]; then
echo "|_. 方向|_. プロトコル|_. ポート|_. IPアドレス|"
for LINE in `cat ${TMPFILE}`
do
  LINE=`echo ${LINE} | sed -e "s/[ \t]\+/ /g"`
  if [[ "${LINE}" =~ ^SECURITYGROUPS ]]; then
    flush_line;
  elif [[ "${LINE}" =~ ^IPPERMISSIONSEGRESS ]] || [[ "${LINE}" =~ ^IPPERMISSIONS ]]; then
    flush_line;
    if [[ "${LINE}" =~ ^IPPERMISSIONSEGRESS ]]; then
      DIR="Outbound"
    else
      DIR="Inbound"
    fi
    PORT=`echo ${LINE} | cut -f2 -d' '`
    if [ "${PORT}" == "-1" ]; then
      PORT="All"
    elif [ "${PORT}" == "0" ]; then
      PORT="0-65535"
    fi
    PROTO=`echo ${LINE} | cut -f3 -d' '`
    if [ ! -n "${PROTO}" ]; then
      PROTO="All"
    fi
  elif [[ "${LINE}" =~ ^IPRANGES ]]; then
    IP=`echo ${LINE} | cut -f2 -d' '`
    echo "|${DIR}|${PROTO}|${PORT}|${IP}|"
    ALL_RANGES=false
  elif [[ "${LINE}" =~ ^USERIDGROUPPAIRS ]]; then
    IP=`echo ${LINE} | cut -f2 -d' '`
    echo "|${DIR}|${PROTO}|${PORT}|${IP}|"
    ALL_RANGES=false
  fi
done
flush_line;
fi