How do I change SSH port on CentOS, Ubuntu & Linux

In this chapter, you will learn

  1. How to change default ssh port on Ubuntu, Centos, and another Linux Distribution?
  2. How to allow that port in Firewall.

It's smart to switch the default SSH port 22 to another one for added security on your Linux server.

You can pick any port between 1024 to 65536, but ports 0 to 1023 are reserved for different connections, so using those might clash with other connections.

It's best to select a port between 1024 to 65536.

Before you change the SSH port, make sure to allow your chosen port in the firewall. If you don't, you might get locked out of your server.


Allow Port in Firewall

Here, I'm selecting port 3553 to allow in the firewall, and then I'll set the SSH port later.

Step 1: Login to your server.
Step 1: Type the following command in sequence.
sudo ufw allow 22
$sudo ufw allow 3553
$sudo ufw enable
$sudo ufw status

Now that ports 22 and 3553 are enabled in the firewall, you can proceed to the next step to change the SSH port to 3553.

Change SSH port?

Step 1: Login to your server.
Step 2: Open the /etc/ssh/sshd_config file in text editor.
sudo vi /etc/ssh/sshd_config
Step 3: Search for "Port 22" and change it to "Port 3553". Also, remember to remove the "#" tag from the beginning of the line.
# The strategy used for options in the default sshd_config shipped with # OpenSSH is to specify options with their default value where # possible, but leave them commented. Uncommented options override the # default value. Include /etc/ssh/sshd_config.d/*.conf #Port 22 Port 3553 #AddressFamily any #ListenAddress 0.0.0.0 #ListenAddress :: #HostKey /etc/ssh/ssh_host_rsa_key #HostKey /etc/ssh/ssh_host_ecdsa_key #HostKey /etc/ssh/ssh_host_ed25519_key
Step 4: To Save & Exit, Press Esc:wq → Press Enter.

Restart the SSH service.

Debian/Ubuntu
sudo systemctl restart ssh.service

or,

sudo service ssh restart
RHEL/CentOS
sudo systemctl restart sshd.service

Login to Server

After changing the ssh port, you can login to your server as follows:

Syntax
ssh -p 3553 username@your_host_address
Example:
ssh -p 3553 [email protected]

Summary

In this tutorial, we covered how to allow a port in the firewall and then change the SSH port on a Linux server.