Security

Change SSH Port

How to change SSH port to reduce automatic brute force attempts from bots and scanners on the internet

The default SSH port is 22. Changing it significantly reduces the number of automatic login attempts from bots and scanners on the internet, though it's not a complete security measure (must always be combined with SSH keys and Fail2ban).


Procedure

1. Open the SSH Configuration File

nano /etc/ssh/sshd_config

2. Find the Port Line and Modify It

Look for:

#Port 22

Uncomment it and change the number (choose a port between 1024 and 65535, e.g., 2222):

Port 2222

3. Open the New Port in the Firewall BEFORE Restarting SSH

# UFW (Debian/Ubuntu)
ufw allow 2222/tcp

# firewalld (CentOS/AlmaLinux)
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload

4. Restart the SSH Service

systemctl restart sshd

5. Test the New Connection (WITHOUT Closing the Current Session)

Open a new terminal and try to connect with the new port:

ssh -p 2222 root@SERVER_IP

Don't close your current SSH session until you've verified that the new connection works. If there's an error, you can still fix it from the open session.

ufw delete allow 22/tcp
ufw deny 22/tcp

Connecting With Custom Port

From now on, you must always specify the port:

ssh -p 2222 root@SERVER_IP

To avoid specifying it every time, add the server to ~/.ssh/config:

Host my-server
    HostName SERVER_IP
    User root
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Then you can connect simply with:

ssh my-server

Changed Port and Now Can't Connect

If you changed the port but can't connect anymore:

  1. Use the VNC Console from the VirtFusion panel
  2. Verify that the firewall allows the new port: ufw status or iptables -L -n
  3. Verify that sshd is listening on the new port: ss -tlnp | grep sshd
  4. Check for errors: journalctl -u sshd -n 20

On this page