How to Close Open Ports in Ubuntu?
Problem Description#
List all open ports to close ports of certain applications.
Best Solution#
To close a port, you need to terminate the process or stop the related service.
You can use the tools netstat -nalp and lsof -i to identify the process/binary behind the open port.
Netstat can be used to view port statistics.
To display a list of all open ports:
sudo netstat -lnp
It lists all listening port numbers and the corresponding processes responsible for them. Terminate or kill the processes to close the ports. (kill, pkill...)
To close an open port:
sudo fuser -k port_no/tcp
Example:
sudo fuser -k 8080/tcp
Alternative Solution#
To close open ports in Ubuntu, you can use the following command:
sudo kill $(sudo lsof -t -i:3000)
Replace 3000 with your desired port number.
The lsof command provides information about files opened by processes.
-t: This flag specifies that lsof should produce concise output with only process identifiers and no headers, for example, to allow the output to be piped to kill(1). This option selects the -w option.
-i: This flag selects a list of files for any Internet address matching the address specified in i. If no address is specified, this option selects a list of all Internet and x.25 (HP-UX) network files.
Applying Firewall Rules#
sudo ufw allow 22
sudo ufw deny 22
Note#
To close a specific process:
kill $(ps -e|grep firefox|awk '{print $1}')