Change Default Port
In this step, we'll modify the default SSH port from 22 to a custom port (2222 in our example). This is an important security measure because many automated bots and attackers scan for SSH servers on the standard port 22. By changing to a non-standard port, we make our server less visible to these automated scans.
Before making any changes, let's first check the current SSH port configuration. This helps us understand the existing setup:
sudo grep -i port /etc/ssh/sshd_config
You'll typically see #Port 22
in the output. The #
symbol means this line is commented out, so SSH is currently using the default port 22.
Now we'll edit the SSH configuration file. We'll use the nano text editor, which is user-friendly for beginners:
sudo nano /etc/ssh/sshd_config
Inside the file, look for the line containing #Port 22
. We need to make two changes here:
- Remove the
#
to uncomment the line (this activates the setting)
- Change the port number from 22 to 2222
The modified line should look like this:
Port 2222
After making this change, save the file in nano by pressing:
- Ctrl+O (to write the file)
- Enter (to confirm the filename)
- Ctrl+X (to exit the editor)
For the changes to take effect, we need to restart the SSH service:
service ssh restart
Let's verify that SSH is now listening on our new port (2222) instead of the default port:
sudo netstat -tulnp | grep ssh
The output should show SSH listening on port 2222. If you still see port 22, double-check your configuration file changes.
Finally, test the new configuration by connecting to SSH using the custom port. Notice we need to specify the port with -p
flag now:
ssh -p 2222 -i ~/.ssh/labex_key localhost
After successfully connecting, you can exit the SSH session by pressing Ctrl+D. Remember that from now on, you'll always need to specify this custom port when connecting to your SSH server.