Skip to content

Ports

What is listening on this computer's TCP ports, with a Kill button. A tool for this computer only, so it doesn't sync.

by MArk · Version 1 · Updated 5 days ago

Price
Free
Works on
Mac
Permissions
2

What it does

  • Lives where you glance

    Menu bar, TailApps Dock, Dashboard and a floating window on your Mac.

  • Stays up to date

    Runs its script ports.sh on your Mac every 10 seconds

What it may do

TailApps shows this list before installing and asks you once. The card can do nothing else.

  • Run its script ports.sh

    script:ports.sh

  • Run its script kill-port.sh

    script:kill-port.sh

Scripts

Everything it runs is here to read before you install.

kill-port.sh
#!/bin/sh
# Stop whatever is listening on TCP port $1 (lsof on a Mac, lsof or ss on Linux)
case "$1" in ''|*[!0-9]*) echo "Not a port: $1" >&2; exit 1 ;; esac
lsof=/usr/sbin/lsof
[ -x "$lsof" ] || lsof=$(command -v lsof)
if [ -n "$lsof" ]; then
  pids=$("$lsof" -t -nP -iTCP:"$1" -sTCP:LISTEN | grep -vx "$TAILAPPS_PID")
elif command -v ss >/dev/null 2>&1; then
  pids=$(ss -Hltnp "sport = :$1" 2>/dev/null | grep -o 'pid=[0-9]*' | cut -d= -f2 | sort -u | grep -vx "$TAILAPPS_PID")
else
  echo "Needs lsof or ss to stop a port" >&2
  exit 1
fi
if [ -z "$pids" ]; then
  echo "Nothing you can stop is listening on port $1" >&2
  exit 1
fi
kill $pids
ports.sh
#!/bin/sh
# Listening TCP ports as JSON: [{"port":5432,"command":"postgres","pid":812}, …]
# TailApps' own process ($TAILAPPS_PID) is left out: apps can't stop TailApps.
# lsof on a Mac (and on Linux when it's installed), else ss on Linux, which only names your own processes.
lsof=/usr/sbin/lsof
[ -x "$lsof" ] || lsof=$(command -v lsof)
if [ -n "$lsof" ]; then
  "$lsof" -nP -iTCP -sTCP:LISTEN -F pcn 2>/dev/null | awk -v self="$TAILAPPS_PID" '
  /^p/ { pid = substr($0, 2); skip = (pid == self) }
  /^c/ { cmd = substr($0, 2); gsub(/["\\]/, "", cmd) }
  /^n/ && !skip {
    port = substr($0, 2); sub(/.*:/, "", port)
    key = pid ":" port
    if (!(key in seen)) {
      seen[key] = 1
      printf "%s{\"port\":%s,\"command\":\"%s\",\"pid\":%s}", (count++ ? "," : "["), port, cmd, pid
    }
  }
  END { print (count ? "]" : "[]") }'
elif command -v ss >/dev/null 2>&1; then
  ss -Hltnp 2>/dev/null | awk -v self="$TAILAPPS_PID" '
  {
    port = $4; sub(/.*:/, "", port)
    cmd = ""; pid = 0
    if (match($0, /users:\(\("[^"]*",pid=[0-9]+/)) {
      s = substr($0, RSTART + 9, RLENGTH - 9); cmd = s; sub(/".*/, "", cmd); pid = s; sub(/.*pid=/, "", pid)
      gsub(/["\\]/, "", cmd)
    }
    if (pid == self && pid != 0) next
    key = pid ":" port
    if (!(key in seen)) {
      seen[key] = 1
      printf "%s{\"port\":%s,\"command\":\"%s\",\"pid\":%s}", (count++ ? "," : "["), port, (cmd == "" ? "?" : cmd), pid
    }
  }
  END { print (count ? "]" : "[]") }'
else
  echo "Needs lsof or ss to list ports" >&2
  exit 1
fi