How to Change the SSH Port in Linux

In Linux, SSH (Secure Shell) is the tool for accessing the server remotely that encrypts the communication between the private server and the client. Using the TCP (Transmission Control Protocol) port 22 has some security threats, such as cyber-attacks. It is the best way to change your default port to protect sensitive data.

This article will demonstrate the method for changing the SSH port in Linux. The content of the post is as follows:

Let’s get into the process of changing the SSH port.

How to Change the SSH Port in Linux?

There are various ports (channels) used by other protocols such as TCP, UDP, FTP, etc. Users can choose any number of ports ranging between 1024 to 49151 (ports from 1 to 1023 are reserved for services). To check the ports used by other services, you can access the services file in the “etc.” directory:

$ cat /etc/services

In the above image, we can see that our default SSH port is 22.

Let’s move and change the SSH port 22 to 5555 in the below steps.

Step 1: Adjust the Firewall

Update the firewall setting that enables the connection to the new port. To do so, run the following command:

$ sudo ufw allow 5555/tcp

The firewall will be updated.

For CentOS:

$ sudo firewall-cmd --permanent --zone=public --add-port=5555/tcp
$ sudo firewall-cmd --reload

Step 2: Configure the SSH File

Now, configure the “ssh_config” file using an editor such as nano and search for the “Port 22” which is commented in the file. Uncomment it, update the port number

$ sudo nano /etc/ssh/ssh_config

After updating the port number, save the file by pressing “Ctrl+O” and exit from the file by pressing “Ctrl+X”.

Step 3: Restart the SSH service

Once you have performed the above operations, restart the SSH service:

$ sudo systemctl restart ssh

Note: The command may not work for a few distributions; in such case, you may use the following command.

$ sudo systemctl restart sshd.service

Step 4: Verifying the Port

Let’s verify whether the port is changed or not using the given command:

$ ss -an | grep 5555

The port 5555 is running can be seen in the above image.

How to Use the New SSH Port?

To use the new SSH port in the connection using the command line interface, use the given command with your remote host:

$ ssh -p 5555 username@remote_host

Or if you are using a GUI version such as putty, change the port number from 22 to 5555 while creating the connection:

That’s all for changing the SSH port.

Conclusion

In Linux, to change the ssh port, update the firewall setting, change the port number in the “ssh_config” file, and restart the ssh service. Use that port number while creating the connection with the remote host. This write-up has illustrated the method for changing the ssh port number in Linux.