Network and Server administration is one of the key areas in which Linux is actually preferred to any other operating system. Hence most data center admins are well versed with the Linux command line.
There can be scenarios when certain ports on a server, which were required to be closed, are open and causing unexpected traffic on the server.
Today, we will learn how to find and close an open port in Linux.
Finding Open Ports in Linux
For finding the open ports, we will make use of the ss command, which is preinstalled in most common Linux distributions and it is now the replacement for the previously very popular netstat command.
Let’s run the ss command with the following syntax, to get all listening TCP sockets:
$ ss -tl
't' stands for TCP and the
'l' stands for Listening sockets.
Similarly to get all listening UDP ports, run:
$ ss -ul
Observe the output. In the ‘State‘ column for UDP, all the ports have state UNCONN, i.e., unconnected. Since we only need the ports which are actively listening, we pipe the output and filter it with the grep command.
$ ss -ul | grep LISTEN
We can also combine the TCP and UDP output together.
$ ss -tul | grep LISTEN
Another addition that can be done here is: the argument
'-n'. In the output above, the command is resolving the name of the service associated with a port: Eg. HTTP, IPP, etc.
With the argument
'-n' it just shows the port number which is listening.
$ ss -tuln | grep LISTEN
Closing Open Ports in Linux
The manual way to close an open port in Linux is quite tedious and programmatic. Hence, we will use the easier approach: to close the processes which are listening on the port.
We need to call ss with another argument,
'-p' to list the process which is using each port (run the command as a sudo user).
$ sudo ss -tulnp | grep LISTEN
As shown above, the last column lists the ‘users’, i.e., the processes which use the port number. Now you can close the port by terminating the process using it. For example, to close port 80, we have to stop the process ‘Apache2’.
$ sudo service apache2 stop OR $ sudo systemctl stop apache2
Thus, we have successfully closed port 80 and no process is listening on it any longer.
In this article, we learned how to find and close an open port in Linux. Many ports like 22 (SSH), 21 (Telnet), etc. should be kept closed at most times, as these are the ports from which cyber attacks can arise.
Other ports should also be closed when the process of using them is no longer required. Thanks for reading and let us know your thoughts in the comments below!