Linux - How to change the connection port number for SSH

Linux - How to change the connection port number for SSH

Colleagues hello to all.

In today's article, we'll talk about how to change the default SSH connection port in Linux.

When connecting to a server using the SSH protocol, the default connection port 22 is used. Using the standard connection port greatly increases the risk of your server being compromised by various brute-force attacks. One of the ways you can protect yourself is to change the standard connection port 22 to some other one.

We will change the port from 22 to 2222.

 

Article content:

  1. Checking the list of open ports.
  2. Add a port to the Firewall.
  3. Add a port to SELinux.
  4. Change the SSH connection port.
  5. Restarting the SSH service.
  6. Check.

 

1. Checking the list of open ports.

First of all, we need to check which ports are currently in use so that we don't accidentally occupy this port. In order to check all open ports we use the command:

$. netstat -tupln | grep LISTEN

change ssh port

As we can see now, ports 22 and 3306 are occupied on our server.


 

2. Adding a port to the Firewall.

Before changing the port, we need to add this port to the Firewall rules so that we do not lose access to the server after changing it. To add a rule, use the command:

$. firewall-cmd --zone=public --add-port=2222/tcp --permanent

After adding a new rule, do not forget to restart all rules.

$. firewall-cmd --reload

change ssh port


 

3. Adding a port to SELinux.

By default SELinux only allows port 22 for SSH, now we need to add port 2222 to SELinux. Run the following command:

$. semanage port -a -t ssh_port_t -p tcp 2222

If the command does not work for you, then install the package policycoreutils-python.

$. sudo yum -y install policycoreutils-python


 

4. Change the SSH connection port.

The next step after checking the ports, we can already change it. All settings for SSH connection are in the  sshd_config file located in the  /etc/ssh directory. We need to open this file and find the parameter called Port and change the values ​​from 22 to something else.

$. vim /etc/ssh/sshd_config

change ssh port

We changed port 22 to 2222.


 

5. Restarting the SSH service.

After the changes we made, we need to restart the SSH service for all our changes to take effect. To restart the service, you can use two commands.

$. systemctl restart sshd.service

or

$. /etc/init.d/sshd restart


 

6. Check.

$. netstat -tupln | grep LISTEN

change ssh port


 

Thank you all, I hope that my article helped you in some way.

 

SIMILAR ARTICLES

Ubuntu - How to open ssh port with ufw
Ubuntu - How to open ssh port with ufw
SAFETY
Firewall - ufw status inactive on Ubuntu
Firewall - ufw status inactive on Ubuntu
SAFETY
Firewall - How to see open ports in Linux
Firewall - How to see open ports in Linux
SAFETY