What you will read?
If you’re looking to enhance your server’s security, one of the simplest yet effective methods is to change the default SSH port from 22 to a custom port. This can help reduce the number of automated attacks your server faces. In this guide, we’ll walk you through the steps to change the SSH port on a Linux server.
Step 1: Connect to Your Server
Before making any changes, connect to your server via SSH using the default port (22):
ssh username@your_server_ip
Step 2: Backup the SSH Configuration File
It’s always a good practice to back up configuration files before making changes. You can do this by running:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
This command creates a backup of the sshd_config
file, which is crucial for SSH settings.
Step 3: Edit the SSH Configuration File
Now, open the SSH configuration file in your favorite text editor. Here, we’ll use nano
:
sudo nano /etc/ssh/sshd_config
Now, open the SSH configuration file in your favorite text editor. Here, we’ll use nano:
sudo nano /etc/ssh/sshd_config
Look for the line that specifies the port. It usually looks like this:
#Port 22
Uncomment this line (remove the #
) and change 22
to your desired port number, for example 2222
:
Port 2222
Make sure to choose a port number between 1024 and 65535, as ports below 1024 are reserved for system use.
Step 4: Adjust the Firewall
After changing the SSH port, you need to allow the new port through your firewall. If you’re using UFW
, you can do this with the following commands:
sudo ufw allow 2222/tcp sudo ufw delete allow 22/tcp
For firewalld
, use:
sudo firewall-cmd --zone=public --add-port=2222/tcp --permanent sudo firewall-cmd --zone=public --remove-port=22/tcp --permanent sudo firewall-cmd --reload
Step 5: Restart the SSH Service
For the changes to take effect, restart the SSH service:
sudo systemctl restart sshd
Step 6: Test the New SSH Port
Before logging out of your current session, it’s wise to test the new port to ensure everything is functioning correctly. Open a new terminal window and try to connect using the new port:
ssh -p 2222 username@your_server_ip
If everything is set up correctly, you should be able to log in without issues.