Changing the SSH port on Linux
-
Access the SSH configuration file: Open a terminal or an existing SSH connection and access the SSH configuration file. This file is usually located at
/etc/ssh/sshd_config. You can open it with a text editor likenano.sudo nano /etc/ssh/sshd_config
You will need superuser (root) permissions to edit this file.
-
Find the line specifying the port: Look for the line that starts with
Port. By default, this line is usually commented out (preceded by#).#Port 22
If it's already present and commented out, remove the # and change the port number (default is 22) to the new port you want to use. For example, to change it to port 2222:Port 2222
If it's not present, you can add it at the end of the file.
-
Save the changes: Save the file after making the modifications. In
nano, pressCtrl+Oto save andCtrl+Xto exit.
-
Ensure the new port is allowed in the firewall: If you have a firewall enabled on your server, make sure to allow the new port.
-
For example, if you're using
ufwon Ubuntu:sudo ufw allow 2222/tcp
Replace2222with the port number you have configured.
-
If you are using a Red Hat-based distribution:
sudo firewall-cmd --permanent --add-port=2222/tcp
Replace2222with the port number you have configured. After adding the port, you need to reload the firewall for the changes to take effect.sudo firewall-cmd --reload
-
For example, if you're using
- Restart the SSH service: To apply the changes, restart the SSH service. This can be done with the following command:
sudo systemctl restart sshd
If you're not usingsystemd, you can use:sudo service sshd restart -
Verify the connection: Before closing the current session, open a new SSH connection specifying the new port to ensure everything is functioning correctly:
ssh user@yourserver -p 2222
Replaceuserwith your username andyourserverwith the IP address or hostname of your server.