Cool script to list processes with open ports
Dave Smith
DavidSmith at byu.net
Tue Nov 1 15:19:00 MST 2005
I stumbled across this little script while googling the fuser program,
which is worth a look if you're not familiar with it. fuser tells you
which PIDs have certain files or network ports open.
This script will list which processes are listening on which TCP/UDP ports:
<snip>
#!/bin/sh
#thanks to ideas of David A.Bandel and Myles Green
#note : fuser requires root priviledge to collect information
netstat -ln |
#keep line that starts with tcp or udp, and keep only protocol and port
sed -e '/^..[^p]/d' -e 's/0.0.0.0:\*.*//1' -e 's/ .*:/ /1' |
while read line
do
# line is of format "tcp port-number" or "udp port-number"
i=`fuser -n $line`
# i is of format "port-number/protocol: PID1 PID2 ..."
#save the part port/protocol for later use
port=`echo $i | sed -e 's/:.*/:/g'`
#get the array of PIDs for a given port/protocol
j=`echo $i | sed -e 's/^.*://g'`
for m in $j # loop for all PIDs
do
#display program that has predefined PID
k=`ps -p $m -o comm -h`
echo "$port $k"
done
done
</snip>
Run it as root for maximum benefit. If you're not root, you'll only see
your own processes.
Enjoy!
--Dave
More information about the PLUG
mailing list