Connect to SSH Server on Alternate Port
Here's a beginner's guide for adding an alternate port to SSH server and the steps for connecting to it.
By default, SSH utilizes port number 22 and many sysadmins change it to avoid the influx of bot attacks trying to brute-force their way in.
If you have to connect to a server via SSH but to a port other than the default one, use:
ssh -p port_number username@ServerIP
Of course, you have to replace the variables like port_number, username and server's IP.
Let me go into detail and show how to add an alternate port of SSH and connect to it.
How to connect to SSH Server using an alternate port
The first step will be to connect to the SSH server and check whether the port you desire to use is already being utilized or not.
Now, let's check whether port no 2222 is being used or not using the ss command:
sudo ss -tulpn | grep ':2222'
As you can clearly see, port no 22 is being used by process ID 889 while port no 2222 is not being utilized making it perfect for our use case.
Now, let's begin with changing firewall rules.
Configure Firewall to access SSH via alternate port
It is always advised to change firewall rules before changing the SSH port especially if you're dealing with a remote server.
As I'll be adding port no. 2222 as an alternate port for SSH, I'm required to use the given command:
sudo ufw allow 2222/tcp
If you are utilizing SELinux, make sure to allow SSH to run on configured alternate port:
sudo semanage port -a -t ssh_port_t -p tcp 2222
Add alternate port to SSH config file
I will keep port 22 and add another port so you can access SSH through both of them.
First, open the SSH config file by the given command:
sudo nano /etc/ssh/sshd_config
Then remove the comment from
Port 22 line and add your desired port just below that:
To make those changes, you will have to restart the ssh service:
sudo systemctl restart sshd
Connect to SSH using an alternate port
As I mentioned earlier, I have kept port no 22 as it is so if you find any error, you can always troubleshoot VM via the default port.
You will have to specify the alternate port with
-p option as shown:
ssh -p 2222 user@ServerIP
And you can always use the old default way (with port 22). For example, I have used multiple terminal windows with default and alternate ports:
This was my take on how you can add an alternate port to access SSH while keeping the default port as it is.
I hope this helps you and if you find any difficulties, make sure to SSH them the comments.