From 9154ec107881ca5b30dcf964ae3929b02270f585 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Mon, 21 Sep 2026 17:20:21 +0300 Subject: [PATCH] Add netstat-tulp.sh --- netstat-tulp.sh | 98 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 netstat-tulp.sh diff --git a/netstat-tulp.sh b/netstat-tulp.sh new file mode 100644 index 0000000..03ba140 --- /dev/null +++ b/netstat-tulp.sh @@ -0,0 +1,98 @@ +#!/bin/ksh + +# OpenBSD equivalent-ish to: +# +# Linux: netstat -tulpn +# +# Shows listening TCP sockets and UDP sockets together with +# the process using the socket when fstat can identify it. +# +# Best run as root for complete process information. + +printf "%-5s %-7s %-8s %-22s %-22s %s\n" \ + "PROTO" "PID" "USER" "LOCAL ADDRESS" "FOREIGN ADDRESS" "PROCESS" + +printf "%-5s %-7s %-8s %-22s %-22s %s\n" \ + "-----" "-------" "--------" "----------------------" \ + "----------------------" "-------" + +# ------------------------------------------------------------ +# TCP listening sockets +# ------------------------------------------------------------ + +netstat -an -f inet 2>/dev/null | +awk '$1 ~ /^tcp/ && $6 == "LISTEN" { + print $1, $4, $5 +}' | +while read proto local foreign +do + # Extract port from local address. + port="${local##*.}" + + # Try to find the process owning this socket. + owner="$( + fstat 2>/dev/null | + awk -v port="$port" ' + $0 ~ ("\\*:" port "([^0-9]|$)") || + $0 ~ ("\\." port "([^0-9]|$)") { + print $1, $2, $3 + exit + } + ' + )" + + if [ -n "$owner" ]; then + set -- $owner + + user="$1" + process="$2" + pid="$3" + else + user="-" + process="-" + pid="-" + fi + + printf "%-5s %-7s %-8s %-22s %-22s %s\n" \ + "$proto" "$pid" "$user" "$local" "$foreign" "$process" +done + + +# ------------------------------------------------------------ +# UDP sockets +# ------------------------------------------------------------ + +netstat -an -f inet 2>/dev/null | +awk '$1 ~ /^udp/ { + print $1, $4, $5 +}' | +while read proto local foreign +do + port="${local##*.}" + + owner="$( + fstat 2>/dev/null | + awk -v port="$port" ' + $0 ~ ("\\*:" port "([^0-9]|$)") || + $0 ~ ("\\." port "([^0-9]|$)") { + print $1, $2, $3 + exit + } + ' + )" + + if [ -n "$owner" ]; then + set -- $owner + + user="$1" + process="$2" + pid="$3" + else + user="-" + process="-" + pid="-" + fi + + printf "%-5s %-7s %-8s %-22s %-22s %s\n" \ + "$proto" "$pid" "$user" "$local" "$foreign" "$process" +done