Linux Block Port With IPtables Command

You can block access to a specific port in Linux using the iptables command. Here’s an example of how you can block access to port 22 (which is used for SSH access) with iptables:

iptables -A INPUT -p tcp --dport 22 -j DROP

This will add a new rule to the INPUT chain, which specifies that packets with the TCP protocol and destination port 22 should be dropped (rejected).

Note that the changes you make with iptables are not persistent across reboots. To make the changes permanent, you will need to save the iptables rules to a file and configure your system to automatically load the rules on startup.

Here’s an example of how you can save the iptables rules to a file:

iptables-save > /etc/iptables.rules

And here’s an example of how you can configure your system to load the iptables rules on startup (on Debian-based systems):

echo '#!/bin/sh' > /etc/network/if-pre-up.d/iptables
echo 'iptables-restore < /etc/iptables.rules' >> /etc/network/if-pre-up.d/iptables
chmod +x /etc/network/if-pre-up.d/iptables

This will create a shell script that restores the iptables rules from the saved file, and configure it to run automatically when the network is brought up.

Leave a Comment