Skip to content

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:

ss -tnlp | grep '2222'

If the command outputs nothing, the port is free and can be used.


2. Change SSH settings

Open the SSH configuration file:

sudo nano /etc/ssh/sshd_config

Find the line:

#Port 22

Remove the # at the beginning of the line (this “uncomments” it) and replace 22 with your new port, e.g.:

Port 2222

Save the file and exit the editor (in nanoCtrl+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):
sudo systemctl restart ssh
  • Ubuntu 24.04:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
  • CentOS, Rocky Linux and other RHEL‑based systems:
sudo systemctl restart sshd

4. Verify that SSH is listening on the new port

Run the same command as at the start:

ss -tnlp | grep '2222'

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:

sudo ufw allow 2222/tcp
sudo ufw reload

(Replace 2222 with your port.)


6. Connect to the server using the new port

Now you must specify the port manually when connecting:

ssh -p 2222 username@ip_address
  • 2222 – your new port
  • username – the user name on the server
  • ip_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.

question_mark
Is there anything I can help you with?
question_mark
AI Assistant ×