How to change SSH port on Linux

Why Change SSH Port on Linux

By default, the SSH server uses port 22 , and this is the first place attackers go when trying to hack. Bots constantly scan the Internet and search for open SSH ports, then attacking them with brute force attacks .

Changing the SSH port to a non-standard one (such as 2222 or 2022) is not a complete defense, but it helps reduce the number of automated attacks . This is a simple step towards increasing the security of the server.

How to change SSH port

Please follow the steps below as we have shown:

First, open the configuration file:

nano /etc/ssh/sshd_config

Find the line that says “port 22”. Make sure you select a port that is not currently in use by another service on the system.

Change it to display the following and specify the SSH port you want.

How to Replace SSH Port on Linux

Save the file (CTRL+X, press Enter), then restart the service with the command:

service sshd restart

Next time you want to SSH into your VPS server, you will have to select the port you set.

ssh root@IP-address -p 25552 - in our case.

Updating firewall configuration

If you are actively using firewall, you should now specify a new port for SSH.

For UFW firewall

This firewall is used mainly in Ubuntu and Debian OS.
The command to add a new SSH port:

 ufw allow 2552

For firewalld firewall

This firewall is used mainly in RHEL, more precisely in CentOS, Oracle Linux, Alma Linux, Rocky Linux.
The command to add a new SSH port:

 firewall-cmd --zone=public --add-port=2552/tcp --permanent
 firewall-cmd --reload

For iptables firewall

The most commonly used firewall in most systems.
The command to add a new SSH port is:

iptables -A INPUT -p tcp -m tcp --dport 2552 -j ACCEPT
service iptables save
service iptables reload

Now you can try to connect to your server on the new port:

How to Replace SSH Port on Linux

As you can see, when we try to connect to this port we will get a response that the “fingerprints” have changed and we must add a new one. The end! Now your server is a little bit more protected from attacks.