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_config2. Find the Port Line and Modify It
Look for:
#Port 22Uncomment it and change the number (choose a port between 1024 and 65535, e.g., 2222):
Port 22223. 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 --reload4. Restart the SSH Service
systemctl restart sshd5. 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_IPDon'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)
ufw delete allow 22/tcp
ufw deny 22/tcpConnecting With Custom Port
From now on, you must always specify the port:
ssh -p 2222 root@SERVER_IPTo avoid specifying it every time, add the server to ~/.ssh/config:
Host my-server
HostName SERVER_IP
User root
Port 2222
IdentityFile ~/.ssh/id_ed25519Then you can connect simply with:
ssh my-serverChanged 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 statusoriptables -L -n - Verify that sshd is listening on the new port:
ss -tlnp | grep sshd - Check for errors:
journalctl -u sshd -n 20