How to run and connect SSH server on a different port

Share this article

SSH is used for logging into a remote machine. It provides secure encrypted communications between two untrusted hosts (your machine and remote machine) over an insecure network. By default, SSH runs on port number 22 but we can change this default port to another port.

In this article, we will learn how to change the SSH default port:

Check the port that the SSH server runs on

Got to the SSH server, run the following command to check on which port sshd is running

sudo netstat -ntlp |grep ssh

Check free port on SSH server

We are checking the free port on the SSH server. Run the following command in the server terminal it will show you all used ports.

Command :

netstat -ntlp 

Command output:

In the above snapshot, we can see all the ports which are being used in our SSH server that means we can not use these ports.

In this tutorial, I will use port 1080 as it is not being used.

Change SSH configuration on the SSH server

Now go to the SSH server and open /etc/ssh/sshd_config. Change the port from default 22 to port 1080 (any port of your preference that is not being used) See the snapshot of the changed configuration.

Change SELinux rule

If you are using centos it is important to add the SELinux rule. Use the following command to add the rule. This command will add rule to allow 1080 port to bind with ssh server.

[root@test ~]# semanage port -a -t ssh_port_t -p tcp 1080

Restart SSH server

Inorder to replicate the changes run the following command to restart the server

Command :

sudo service sshd restart

Command output :

How to SSH the server

SSH client by default connects to SSH server on port 22. Now in our case, we have to explicitly mention that we want to connect on port 1080.

Mention port explicitly in the command

You can mention port explicitly in the command for that use -p option in ssh command, command syntax shown as follows

command syntax :

 ssh remoteuser@remotehost -p <port_number>

Command example :

[centos@test ~]$ 
[centos@test ~]$ ssh root@192.168.122.105 -p 1080

Configure ssh client

Create .ssh/config file enter the ssh related configuration into the file. For reference see the following snapshot.

Now to connect the SSH server you have to enter only the name of the server.

Command syntax:

ssh <host_name>

Command example :

[centos@test ~]$ 
[centos@test ~]$ ssh test_server

Summary

In this article, we have seen how to change the default SSH port. Also, how to connect ssh on the changed port.

Leave a Comment

Your email address will not be published. Required fields are marked *