Changing the Default SSH Port¶
By default, SSH connections use port 22. Many hackers automatically scan this port in an attempt to compromise a server. Changing the port to a different one (for example, 2222) makes your server less noticeable and harder to target.
Here is a step-by-step guide on how to do this safely.
-
Make sure the chosen port is free
Before using a new port, verify that it is not already in use by another application. For example, if you want to use port 2222, run the following command:
If the command returns no output — the port is free, and you can use it.
-
Change SSH settings
Open the SSH configuration file:
Locate the line:
Remove the
#at the beginning of the line (this will uncomment it), and replace22with your new port, for example:Save the file and close the editor (in
nano— Ctrl+O, Enter, then Ctrl+X). -
Restart SSH
To apply the changes, restart the SSH service. The command depends on your system:
- Debian, Ubuntu (excluding 24.04):
- Ubuntu 24.04:
- CentOS, Rocky Linux, and other RHEL-based distributions:
-
Verify that SSH is listening on the new port
Run the same command as at the beginning:
If everything is correct, you will see a line with
sshdindicating that the service is now listening on the new port. -
Open the port in the firewall
If your firewall is enabled (for example, UFW), you need to allow connections to the new port:
(Replace
2222with your port.) -
Connect to the server using the new port
Now, when connecting, you must specify the port manually:
2222— your new portusername— the username on the serverip_address— the server's IP address
Attention
Do not close your current SSH session until you have confirmed that the new one works. Otherwise, you may lose access to the server.