Skip to content

Instantly share code, notes, and snippets.

@jcardus
Last active December 26, 2025 23:42
Show Gist options
  • Select an option

  • Save jcardus/6458b9158c5d340e62c02d0c5925c566 to your computer and use it in GitHub Desktop.

Select an option

Save jcardus/6458b9158c5d340e62c02d0c5925c566 to your computer and use it in GitHub Desktop.
traccar connections to cloudwatch
NAMESPACE="Traccar"
INTERVAL=600
REGION="us-east-1"
while true; do
date;
total=$(ss -tanH | wc -l);
echo "Total connections: $total";
aws cloudwatch put-metric-data --namespace "$NAMESPACE" --metric-name "Connections" --value "$total" --unit "Count" --region "$REGION";
# 1) Build a set of listening TCP ports (authoritative)
LISTEN_PORTS="$(ss -tlnH | awk '
{
addr=$4
# Extract last :PORT at end (works for IPv4 and [IPv6]:PORT)
if (match(addr, /:([0-9]+)$/, m)) print m[1]
}' | sort -u)"
# 2) Feed those ports into awk and classify lsof connections
# Incoming: local port is in LISTEN set
# Outgoing: otherwise (group by remote port)
lsof -nP -iTCP -sTCP:ESTABLISHED \
| awk -v ports="$LISTEN_PORTS" '
BEGIN {
n = split(ports, a, "\n")
for (i=1; i<=n; i++) if (a[i] != "") listen[a[i]] = 1
}
{
name = $9 # NAME column: localIP:localPort->remoteIP:remotePort
if (match(name, /^(.*):([0-9]+)->(.*):([0-9]+)$/, m)) {
lport = m[2]
rport = m[4]
total++
if (lport in listen) {
incoming[lport]++
inc_total++
} else {
outgoing[rport]++
out_total++
}
}
}
END {
print "TOTAL ESTABLISHED TCP CONNECTIONS:", total
print ""
print "INCOMING (to local listening ports):"
for (p in incoming) printf "%6d local-port %s\n", incoming[p], p
print ""
print "OUTGOING (to remote ports):"
for (p in outgoing) printf "%6d remote-port %s\n", outgoing[p], p
print ""
print "INCOMING TOTAL:", inc_total
print "OUTGOING TOTAL:", out_total
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment