Linux doesn’t seem to have a direct command to open or close a port. Because if a port is simply opened without associating it with a process, the opening or closing of the port becomes rather pointless (an open port with no program to handle incoming data). In other words, port activity in Linux is closely tied to processes. If you want to close a specific port, you just need to kill the corresponding process.
For example, to close port 22:
$ netstat -anp | grep :22
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1666/sshd
# -a displays all active TCP connections, and TCP/UDP ports that are listening
# -n displays addresses and port numbers in numerical form, without attempting to resolve their names
# -p lists the processes associated with the port listening or connection (note: there is a caveat mentioned below) (pid)
Now that we know the process ID 1666 corresponds to port 22, simply:
$ kill 1666
and it’s done.
The “-p” option requires attention regarding permissions. If you run the netstat command in a shell logged in as a regular user, you can only list processes associated with that user’s privileges. To see all port statuses, it is best to switch to root.
A few additional common netstat option usages:
$ netstat -tn # Lists the connection status of all TCP protocols
# -t only displays connections and port listening status related to the TCP protocol, note this differs from -a (tcp)