How to Close Open Ports in Ubuntu?
Problem Description#
List all open ports to close ports used by certain applications.
Best Solution#
To close a port, you must terminate the process or stop the related service.
You can use the netstat -nalp and lsof -i tools 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 instructs lsof to produce concise output with only process identifiers and no headers, for example, so that the output can be piped to kill(1). This option selects the -w option.
-i: This flag selects a list of files for any Internet address that matches 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}')