Skip to content

Changing the Default SSH Port

By default, SSH connections use port 22. Many hackers automatically scan this port in an attempt to compromise a server. Changing the port to a different one (for example, 2222) makes your server less noticeable and harder to target.

Here is a step-by-step guide on how to do this safely.

  1. Make sure the chosen port is free

    Before using a new port, verify that it is not already in use by another application. For example, if you want to use port 2222, run the following command:

    ss -tnlp | grep '2222'
    

    If the command returns no output — the port is free, and you can use it.

  2. Change SSH settings

    Open the SSH configuration file:

    sudo nano /etc/ssh/sshd_config
    

    Locate the line:

    #Port 22
    

    Remove the # at the beginning of the line (this will uncomment it), and replace 22 with your new port, for example:

    Port 2222
    

    Save the file and close the editor (in nanoCtrl+O, Enter, then Ctrl+X).

  3. Restart SSH

    To apply the changes, restart the SSH service. The command depends on your system:

    • Debian, Ubuntu (excluding 24.04):
    sudo systemctl restart ssh
    
    • Ubuntu 24.04:
    sudo systemctl daemon-reload
    sudo systemctl restart ssh.socket
    
    • CentOS, Rocky Linux, and other RHEL-based distributions:
    sudo systemctl restart sshd
    
  4. Verify that SSH is listening on the new port

    Run the same command as at the beginning:

    ss -tnlp | grep '2222'
    

    If everything is correct, you will see a line with sshd indicating that the service is now listening on the new port.

  5. Open the port in the firewall

    If your firewall is enabled (for example, UFW), you need to allow connections to the new port:

    sudo ufw allow 2222/tcp
    sudo ufw reload
    

    (Replace 2222 with your port.)

  6. Connect to the server using the new port

    Now, when connecting, you must specify the port manually:

    ssh -p 2222 username@ip_address
    
    • 2222 — your new port
    • username — the username on the server
    • ip_address — the server's IP address

Attention

Do not close your current SSH session until you have confirmed that the new one works. Otherwise, you may lose access to the server.

question_mark
Is there anything I can help you with?
question_mark
AI Assistant ×