By default, port 22 is defined for SSH in Linux. Changing the default port can help increase server security and may reduce automated SSH attacks.
In this tutorial, we will explain how to change the SSH port and define it in the Linux firewall.
Change SSH port
To change the default SSH port to a desired port, follow these steps:
Select a new port number
Some ports are reserved by Linux services. So you should be careful not to choose these numbers. We recommend choosing a number higher than 1024.
For example, we want to change the SSH port to 7743.
Firewall settings
Before changing the SSH port, the new port first needs to be allowed or opened in the firewall.
Ubuntu: If you are using the UFW firewall on Ubuntu (the default firewall of the operating system), the following command is used to open port 7743:
sudo ufw allow 7743/tcp
CentOS: In CentOS operating system, firewall management is done by FirewallD by default. You can use the following command to open port 7743 in FirewallD:
sudo firewall-cmd --permanent --zone=public --add-port=7743/tcp
sudo firewall-cmd --reload
If you are using iptables as a firewall, you can use the following command to open port 7743:
sudo iptables -A INPUT -p tcp --dport 7743 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
If SELinux is enabled on the operating system, you can use the following command to add a new port to the SELinux rules:
sudo semanage port -a -t ssh_port_t -p tcp 7743
SSH Configuration
Open the SSH configuration file at /etc/ssh/sshd_config with a text editor:
sudo nano /etc/ssh/sshd_config
Find the line that says Port 22. This line usually has a # symbol at the beginning. Remove the # symbol and change the number 22 to 7743.
Be careful when modifying the SSH configuration file. Incorrect configuration may prevent the SSH service from running.
Then save the file and restart the SSH service using the following command:
sudo systemctl restart ssh
In CentOS, the following command is used to restart SSH:
sudo systemctl restart sshd
The SSH port has now changed and you can connect to the server through the new port.