Knowledge Base

How to Change SSH Port in Linux

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:


1. 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

2. Edit the SSH Configuration File

Open the SSH configuration file using a text editor like nano:

sudo nano /etc/ssh/sshd_config

3. 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

4. Save and Exit

In nano, press Ctrl + O to save the changes, then Enter to confirm. Press Ctrl + X to exit the editor.

5. Update Firewall Rules

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

6. Restart the SSH Service

Apply the changes by restarting the SSH daemon:

sudo systemctl restart sshd

7. Test the New SSH Port

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.


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.

Please rate this article to help us improve our Knowledge Base.

0 0