Many times it is required to know which process is running on a specific port. The application which you are installing may be giving an error such as “can not bind the port” or “the port is already in use”. In these cases we can determine which process has blocked the port. There are also audit requirements sometimes, for finding out all the port and associated processes.
To solve this issue, there is a simple script available (credits to oracle). The script does the following :
1. Loops through all the process directories in /proc
2. Runs pfiles command on each directory while grepping for AF_INET and the port specified as an argument to the script.
3. If the error code returned is 0 ( i.e. success) , the process using the port is echoed out.
2. Runs pfiles command on each directory while grepping for AF_INET and the port specified as an argument to the script.
3. If the error code returned is 0 ( i.e. success) , the process using the port is echoed out.
The complete script is as below :
#!/bin/bash # Get the process which listens on port # $1 is the port we are looking for if [ $# -lt 1 ] then echo "Please provide a port number parameter for this script" echo "e.g. $0 22" exit fi echo "Greping for your port, please be patient (CTRL+C breaks) ... " for i in `ls /proc` do pfiles $i | grep AF_INET | grep $1 if [ $? -eq 0 ] then echo Is owned by pid $i fi done
To find the processes using the port 22, run the script as :
# ./port.sh 22 Greping for your port, please be patient (CTRL+C breaks) ... sockname: AF_INET6 ::ffff:192.168.1.20 port: 22 Is owned by pid 3657 sockname: AF_INET6 ::ffff:192.168.1.20 port: 22 Is owned by pid 3658 sockname: AF_INET6 :: port: 22 Is owned by pid 824
Check for the processes :
# ps -ef | egrep "3657|3658|824" root 3657 824 0 07:57:51 ? 0:00 /usr/lib/ssh/sshd root 824 1 0 04:09:51 ? 0:00 /usr/lib/ssh/sshd root 3658 3657 0 07:57:51 ? 0:01 /usr/lib/ssh/sshd
Script to find all the open ports
The script below can be used to find all the open ports
#!/bin/ksh # open_ports.ksh script # pfexec pfiles /proc/* 2>/dev/null | nawk -v port=$1 ' /^[0-9]/ { cmd=$0; type="unknown"; continue } $1 == "SOCK_STREAM" { type="tcp" } $1 == "SOCK_DGRAM" { type="udp" } $2 == "AF_INET" { if((port!="")&&($5!=port)) continue; if(cmd!="") { printf("%sn %s:%s/%sn",cmd,$3,$5,type); cmd="" } else { printf(" %s:%s/%sn",cmd,$3,$5,type); }}'
Run the script to display all the open ports in the server :
# ./open_ports.ksh 1920: /usr/sbin/in.routed 0.0.0.0:520/udp :0.0.0.0/0 5830: /usr/lib/sendmail -bl -q15m 127.0.0.1:25/tcp :127.0.0.1/587 767: /usr/sbin/rpcbind 0.0.0.0:111/unknown :0.0.0.0/0 :0.0.0.0/41986 :0.0.0.0/111 :0.0.0.0/0 85: /lib/inet/in.mpathd 0.0.0.0:0/udp :127.0.0.1/5999