Changing the default SSH port on your Linux server enhances security by reducing the risk of automated attacks targeting port 22.
Follow these steps to change the SSH port:
- Backup the SSH Configuration File
Before making any changes, create a backup of the SSH configuration file:sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup - Edit the SSH Configuration File
Open the SSH configuration file using a text editor like nano:sudo nano /etc/ssh/sshd_config - Modify the Port Directive
Locate the line starting with Port 22. Uncomment the line (remove the # at the beginning) and change 22 to your desired port number (e.g., 2222):Port 2222 - Save and Exit
In `nano`, press `Ctrl + O` to save the changes, then `Enter` to confirm. Press `Ctrl + X` to exit the editor. - Update Firewall Rules
If you have a firewall enabled (e.g., UFW), allow the new SSH port:
If using firewalld:sudo ufw allow 2222/tcpsudo firewall-cmd --permanent --add-port=2222/tcp sudo firewall-cmd --reload - Restart the SSH Service
Apply the changes by restarting the SSH daemon:sudo systemctl restart sshd - Test the New SSH Port
Open a new terminal session and connect using the new port:
Ensure you can log in successfully before closing your current session.ssh username@your_server_ip -p 2222
Important Considerations
Firewall Configuration: Ensure that your firewall allows traffic on the new SSH port to prevent being locked out.
SELinux Contexts: If SELinux is enabled, update the port contexts:
sudo semanage port -a -t ssh_port_t -p tcp 2222
While changing the SSH port can reduce automated attacks, it is not a substitute for strong authentication methods like key-based authentication.
By following these steps, you can enhance the security of your Linux server by changing the default SSH port.