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:
Before making any changes, create a backup of the SSH configuration file:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
Open the SSH configuration file using a text editor like nano:
sudo nano /etc/ssh/sshd_config
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
In nano
, press Ctrl + O
to save the changes, then Enter
to confirm. Press Ctrl + X
to exit the editor.
If you have a firewall enabled (e.g., UFW), allow the new SSH port:
sudo ufw allow 2222/tcp
If using firewalld:
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
Apply the changes by restarting the SSH daemon:
sudo systemctl restart sshd
Open a new terminal session and connect using the new port:
ssh username@your_server_ip -p 2222
Ensure you can log in successfully before closing your current session.
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.