Change SSH Port

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).

02

Procedure

1. Open the SSH Configuration File

bash
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

bash
# 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

bash
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:

bash
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.

6. Block the Old Port 22 (Optional but Recommended)

bash
ufw delete allow 22/tcp
ufw deny 22/tcp
03

Connecting With Custom Port

From now on, you must always specify the port:

bash
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:

bash
ssh my-server
04

Changed Port and Now Can't Connect

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

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

DeluxHost, founded in 2023, offers high-quality hosting solutions for various digital needs. We provide shared hosting, VPS, and dedicated servers with advanced security and global data centers.

© DeluxHost, All rights reserved. | VAT Number : IT17734661006
All Systems Operational