How To Change SSH Port In Linux

We wrote a detailed article on what SSH is and how to use SSH to connect to a remote server. In this article, you will learn why and how to change the default SSH port.

Why change the default SSH port?

If your Linux distro does not have SSH pre-installed, it’s easy to install. Use the package manager to install SSH or read this article.

When trying to connect to the remote server, the basic command requires the username and the IP of the remote server.

ssh username@ip_address [options]

By default, SSH uses port 22 to allow a connection from any other machine. That is the reason why it is not necessary to mention the port in the command. The ssh command automatically tries to connect the user through port 22.

But it is important to change the default SSH port so that the server drops any automated connection request before it even searches for the user account on the server.

How to change default SSH port?

If you are using any cPanel to manage your server, please refer to their documentation to change it. For example, CentOS cPanel suggests changing the default SSH port right after your first login. Or, read the following instructions to do it manually.

To change the SSH port of the remote server, modify the ssh configuration file that exists in /etc/ssh/ssh_config.

Open the file in nano.

sudo nano /etc/ssh/ssh_config
ssh config file

Now search for the line that says “port 22”. For short, you can press ctrl+w and type “port,” and hit enter.

default ssh port

nano will search the port 22 line that is commented out. First, change the port number from 22 to any other port not already in use by any other application. For the demonstration, I am going to change it from 22 to 3243.

ssh port

Lastly, remove the # to activate the setting.

change ssh port

And that is it. Now the server will require the port to be sent with the ssh command; else, it’ll drop the command with the error.

ssh username@ip_address -p 3243

Reset back to default port

If you want to change ssh port back to the default, comment out the port line in /etc/ssh/ssh_config.