Changing the Default SSH Port¶
By default, SSH connections use port 22. Many hackers automatically scan this port in an attempt to breach the server. If you change the port to another one (for example, 2222), it will make your server less noticeable and harder to attack.
Here is a step‑by‑step guide to do it safely.
1. Ensure the chosen port is free¶
Before using a new port, check that it isn’t already in use by another application. For example, if you want to use port 2222, run:
If the command outputs nothing, the port is free and can be used.
2. Change SSH settings¶
Open the SSH configuration file:
Find the line:
Remove the # at the beginning of the line (this “uncomments” it) and replace 22 with your new port, e.g.:
Save the file and exit the editor (in nano – Ctrl+O, Enter, then Ctrl+X).
3. Restart SSH¶
To apply the changes, restart the SSH service. The command depends on your system:
- Debian, Ubuntu (except 24.04):
- Ubuntu 24.04:
- CentOS, Rocky Linux and other RHEL‑based systems:
4. Verify that SSH is listening on the new port¶
Run the same command as at the start:
If everything is correct, you’ll see a line with sshd indicating that the service is now running on the new port.
5. Open the port in the firewall¶
If your firewall is enabled (e.g., UFW), you need to allow connections to the new port:
(Replace 2222 with your port.)
6. Connect to the server using the new port¶
Now you must specify the port manually when connecting:
2222– your new portusername– the user name on the serverip_address– the server’s IP address
Note
Do not close the current SSH session until you are sure the new one works. Otherwise you may lose access to the server.