I want to change the default SSH port 22 to a different port. Whenever I log in to my server with SSH as root user I can see there are more than 2000+ login fail attempts. So I am thinking of changing the default port of SSH as a countermeasure. Can someone provide clear steps or instructions on how to do this safely?
1. Login as Root
2. Edit SSH Configuration File
3. Find and Change the Port Number:
Within the config file, find the below line
Uncomment the line (remove the
# ) and change the port number to your desired value. For security reasons, it’s best to choose a port number between 1024 and 49151 that is not commonly used.
4. Save and Exit
5. Restart SSH Service:
systemctl restart sshd
sudo systemctl restart sshd
6. Firewall Configuration (if needed):
If you are using a firewall (like firewalld), ensure that the new SSH port is allowed through.
firewall-cmd --add-port=4920/tcp --permanent
Before you close your current SSH session, open a new terminal or SSH client and try connecting to your server using the new port. If you can connect without any issue then you can safely close your SSH sessions.
If SELinux (Security-Enhanced Linux) is enabled on your CentOS 7 server, you’ll need to make some additional adjustments when changing the SSH port.
First Check SELinux Status
If SELinux is enabled, you’ll see output indicating that it is enabled.
Add New Port to SELinux Policy
semanage port -a -t ssh_port_t -p tcp 4920
Now, verify that SELinux has allowed sshd to listen on the two ports:
semanage port -l | grep ssh
You should see the new port in the list 4920. That’s it, you are done, you can now change the port.