Files
OpenBSD-Notes/netstat-tulp.sh
T
2026-09-21 18:17:35 +03:00

145 lines
2.8 KiB
Bash

#!/bin/ksh
#
# ports
#
# Show network sockets with their owning processes.
#
# Similar idea to Linux:
#
# netstat -tulpn
#
# OpenBSD implementation using:
#
# fstat
# ps
#
# Run as root for complete information.
#
# ------------------------------------------------------------
# Header
# ------------------------------------------------------------
printf "%-5s %-28s %-8s %-12s %s\n" \
"PROTO" \
"LOCAL ADDRESS" \
"PID" \
"USER" \
"COMMAND"
printf "%-5s %-28s %-8s %-12s %s\n" \
"-----" \
"----------------------------" \
"--------" \
"------------" \
"-------"
# ------------------------------------------------------------
# Read Internet sockets from fstat
# ------------------------------------------------------------
fstat 2>/dev/null |
awk '
#
# We only want IPv4/IPv6 Internet sockets.
#
$5 == "internet" || $5 == "internet6" {
user = $1
process = $2
pid = $3
family = $5
type = $6
proto = $7
#
# Ignore raw sockets.
#
if (type != "stream" && type != "dgram")
next
#
# Only TCP and UDP.
#
if (proto != "tcp" && proto != "udp")
next
#
# Determine tcp4/tcp6/udp4/udp6.
#
if (family == "internet6")
proto = proto "6"
else
proto = proto "4"
#
# Find the local address.
#
# fstat output contains a kernel socket pointer before
# TCP addresses, for example:
#
# tcp 0xffff800001058140 *:22
#
# UDP normally looks like:
#
# udp 192.168.0.2:37163 <-> ...
#
# Search fields after the protocol for the first field
# containing ":".
#
local = "-"
for (i = 8; i <= NF; i++) {
if ($i ~ /:/) {
local = $i
break
}
}
#
# Print fields separated by tabs so the shell can
# safely parse them.
#
printf "%s\t%s\t%s\t%s\n",
proto,
local,
pid,
user
}
' |
while IFS=' ' read proto local pid user
do
# --------------------------------------------------------
# Get complete command line from PID.
# --------------------------------------------------------
command="$(
ps -p "$pid" -o args= 2>/dev/null
)"
if [ -z "$command" ]; then
command="-"
fi
# --------------------------------------------------------
# Output
# --------------------------------------------------------
printf "%-5s %-28s %-8s %-12s %s\n" \
"$proto" \
"$local" \
"$pid" \
"$user" \
"$command"
done