...
Skip to main content
Print

How to Change the SSH Port on Linux

You change the SSH port in the /etc/ssh/sshd_config file. First open the new port in the firewall, then change the port and restart SSH, so you do not lock yourself out. A different SSH port greatly reduces the number of automated login attempts. It does not replace logging in with an SSH key, but it is a useful extra measure.

Step 1: open the new port in the firewall

Choose a port number, for example 2222, and allow it in the firewall before you change SSH:

ufw allow 2222/tcp

Step 2: change the port in the SSH configuration

Find the Port line, remove the hash in front of it and enter the new port number:

Port 2222

Step 3: restart SSH

First test the configuration and then restart SSH:

sshd -t
systemctl daemon-reload
systemctl restart ssh

On recent Ubuntu versions SSH starts via socket activation. In that case also restart the socket with systemctl restart ssh.socket.

Step 4: connect via the new port

Open a new window and test whether you can log in via the new port. Only close your current session once this works:

ssh -p 2222 root@JOUW-IP

If everything works, remove the old rule for port 22 from the firewall with ufw delete allow OpenSSH.

Changing the SSH port on AlmaLinux

On AlmaLinux you also need to allow the new port in SELinux and firewalld:

semanage port -a -t ssh_port_t -p tcp 2222
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
systemctl restart sshd

Locked out?

If you can no longer log in after the change, use the noVNC console in the client area to restore the setting.

Related articles

Table of Contents