Cool script to list processes with open ports

Byron Clark byron at
Thu Nov 3 08:17:54 MST 2005

On Tue, Nov 01, 2005 at 03:19:00PM -0700, Dave Smith wrote:
> 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/\*.*//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>

Unless I'm missing something 'netstat -lnp' does the same thing, but
with slightly uglier output.

Byron Clark                     |
byron at       | 
GnuPG Fingerprint: 0365 6979 6C3E BC0C 56C0 FB7F 12B3 75DD 042B EA68

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : 

More information about the PLUG mailing list