Interview Prep/Shell Scripting/Scenarios: health checks, monitoring and alerts

Security wants an alert if a server listens on any port not in an approved list. Write it.

IntermediateScenarioScenarios: health checks, monitoring and alerts
Answer

Situation read → Compare the current listening sockets against an allow-list.

What I'd do →

allowed=(22 80 443 9100)
mapfile -t listening < <(ss -Htlnu | awk '{print $5}' | sed -E 's/.*:([0-9]+)$/\1/' | sort -un)
unexpected=$(comm -13 <(printf '%s\n' "${allowed[@]}" | sort -u) <(printf '%s\n' "${listening[@]}"))
if [[ -n $unexpected ]]; then
  echo "CRIT unexpected listening ports: $(paste -sd, <<<"$unexpected")"
  ss -Htlnup | grep -E ":($(paste -sd'|' <<<"$unexpected"))\b"
  exit 2
fi
  1. ss -H drops the header, -p (as root) shows the owning process for the report.
  2. comm -13 prints lines only in the second (current) list.

Why → An unexpected listener is either drift or compromise; both deserve attention.

Interview tip → Mention that comm needs both inputs sorted the same way.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: health checks, monitoring and alerts