How to Check for Listening Ports In Linux (Ports in use)
Netstat is command line utility to check the listening ports
netstat -tunlp | head -5
You will see following output
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 1/systemd
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 30277/nginx: master
tcp 0 0 127.0.0.1:41971 0.0.0.0:* LISTEN 11386/python
The options used in this command have the following meaning:
-t - Show TCP ports.
-u - Show UDP ports.
-n - Show numerical addresses instead of resolving hosts.
-l - Show only listening ports.
-p - Show the PID and name of the listener’s process. This information is shown only if you run the command as root or sudo user.
The output of netstat -tunlp will be list of all the ports, To go through the list pipe it to less
netstat -tunlp | less
Then identified the ports you are looking for, another way is pipe it to grep if you know know the port you are looking for
netstat -tunlp | egrep :22 tcp 0 0 0.0.0.0[01;31m[K:22[m[K 0.0.0.0:* LISTEN 3827/sshd tcp6 0 0 ::[01;31m[K:22[m[K :::* LISTEN 3827/sshd
With grep
netstat -tunlp | egrep :8000 tcp 0 0 127.0.0.1[01;31m[K:8000[m[K 0.0.0.0:* LISTEN 30240/python
Another Great Utility is lsof; To get a list of all listening TCP ports
with lsof type:
lsof -nP -iTCP -sTCP:LISTEN | head -5
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
systemd 1 root 40u IPv4 28515588 0t0 TCP *:111 (LISTEN)
systemd 1 root 43u IPv6 28515590 0t0 TCP *:111 (LISTEN)
ZMQbg/1 1594 root 12u IPv4 53188107 0t0 TCP 127.0.0.1:58229 (LISTEN)
ZMQbg/1 1594 root 14u IPv4 53188109 0t0 TCP 127.0.0.1:58411 (LISTEN)
To find out who is listening on port 8000
lsof -nP -iTCP:8000 -sTCP:LISTEN
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 30240 root 10u IPv4 50135397 0t0 TCP 127.0.0.1:8000 (LISTEN)
Or As explained before, you can also Pipe to egrep or less
lsof -nP -iTCP -sTCP:LISTEN | egrep :8000 python 30240 root 10u IPv4 50135397 0t0 TCP 127.0.0.1[01;31m[K:8000[m[K (LISTEN)
Similarly We can find any listening port such as for mysql on 443
lsof -nP -iTCP:443 -sTCP:LISTEN
For checking MongoDB listening on 27017
lsof -nP -iTCP:27017 -sTCP:LISTEN
For checking ElasticSearch listening on 9200
lsof -nP -iTCP:9200 -sTCP:LISTEN
Thanks for reading