Skip to main content

Changing the Default SSH Port 22 on Linux Ubuntu Server

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Learn how to change the default SSH port 22 on Linux Ubuntu Server. This guide includes setup, firewall updates, testing, and best practices for a secure SSH setup.

Introduction

Secure Shell (SSH) is a widely-used protocol for secure communication with remote servers. However, the default SSH port, 22, is often the target of automated brute-force attacks, which can compromise server security. Changing the default SSH port to a non-standard port adds an extra layer of security by obscurity, helping to mitigate unauthorized access attempts. This blog will walk you through the process of changing the SSH port, along with some security tips and best practices for managing your SSH connections.

Why Change the Default SSH Port?

Here are a few key reasons to consider changing the default SSH port:

  • Reduces Brute-Force Attacks: Since attackers commonly target port 22, changing it to a non-standard port can reduce the frequency of brute-force attacks.
  • Mitigates Bots and Malware: Many automated scripts and malware variants scan for open SSH connections on port 22, so using a different port can help avoid detection.
  • Enhances Security Posture: While not foolproof, moving to a non-standard port is a quick, low-effort enhancement that can add a layer of protection.

Prerequisites

  • Root or Sudo Access: You will need administrative privileges to modify SSH configurations.
  • Basic SSH Knowledge: Familiarity with SSH and server configurations is helpful.
warning

Changing the SSH port affects how you connect to the server. If your firewall, SSH clients, or automation scripts use port 22 explicitly, you’ll need to update them to use the new port.

Step 1: Pick a New SSH Port

The SSH port can be any unused port between 1024 and 65535. Generally, avoid ports used by common services or any ports below 1024 (known as privileged ports). Here are some considerations:

  • Choose a port outside the commonly scanned range, such as between 49152 and 65535, for an added layer of security.
  • Avoid ports associated with other services (e.g., 80 for HTTP, 443 for HTTPS).

For this guide, we’ll assume 3333 as our new port.

Step 2: Modify the SSH Configuration File

  1. Open the SSH Configuration File: SSH settings are stored in the sshd_config file. Use a text editor to open the file. Run:
sudo nano /etc/ssh/sshd_config
  1. Locate the Port Directive: Look for the line that reads #Port 22. By default, it’s commented out with a #.

  2. Change the Port Number:

  • Uncomment the line by removing the #.
  • Replace 22 with the new port number, such as 3333.

Your configuration line should look like this:

/etc/ssh/sshd_config
Port 3333
  1. Save and Exit: Save the changes by pressing Ctrl+X, then Y, and close the file.

Step 3: Configure the Firewall

To allow connections on the new port, update your firewall settings.

For UFW (Uncomplicated Firewall) Users

If you’re using UFW (commonly on Ubuntu):

note

If UFW is not enabled, you can enable it by running:

sudo ufw enable
  1. Allow the new SSH port:
sudo ufw allow 3333/tcp
  1. Deny the default SSH port if no longer needed:
sudo ufw delete allow 22/tcp
  1. Reload UFW to apply changes:
sudo ufw reload

For Firewalld Users

If your system uses Firewalld (common on CentOS/RHEL):

  1. Add the new SSH port:
sudo firewall-cmd --permanent --add-port=3333/tcp
  1. Remove the old port if you don’t need it:
sudo firewall-cmd --permanent --remove-port=22/tcp
  1. Reload Firewalld to apply the new settings:
sudo firewall-cmd --reload

For iptables Users

If you use iptables:

  1. Allow the new port:
sudo iptables -A INPUT -p tcp --dport 3333 -j ACCEPT
  1. Block the default port if not needed:
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
  1. Save the new iptables rules:
sudo iptables-save > /etc/iptables/rules.v4

Step 4: Restart the SSH Service

After making configuration changes, restart the SSH service for them to take effect.

sudo systemctl restart ssh
warning

Important: Do not close your current SSH session until you have tested the new port to ensure it’s working as expected.

Step 5: Test the New SSH Port

Now, open a new terminal window and attempt to connect using the new SSH port.

Local Machine Terminal
ssh -p 3333 username@server-ip

Replace username with your actual username and server-ip with your server’s IP address. If the connection is successful, you can safely close your old SSH session.

Following Error might come

Local Machine Terminal
ssh: connect to host server-ip port 3333: Connection refused

In latest Ubuntu Server 24.x, sometimes restarting the ssh service does not update the SSH port. You can verify the port number for SSH by running the below command:

Ubuntu Server Terminal
sudo systemctl status ssh

Sample output:

ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/usr/lib/systemd/system/ssh.service; disabled; preset: enabled)
Active: active (running) since Sat 2024-10-26 07:32:50 UTC; 2s ago
TriggeredBy: ● ssh.socket
Docs: man:sshd(8)
man:sshd_config(5)
Process: 3002 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
Main PID: 3001 (sshd)
Tasks: 1 (limit: 9312)
Memory: 1.2M (peak: 1.5M)
CPU: 19ms
CGroup: /system.slice/ssh.service
└─3007 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

Oct 26 07:32:50 servername systemd[1]: Starting ssh.service - OpenBSD Secure Shell server...
Oct 26 07:32:50 servername sshd[3001]: Server listening on 0.0.0.0 port 22.
Oct 26 07:32:50 servername sshd[3001]: Server listening on :: port 22.
Oct 26 07:32:50 servername systemd[1]: Started ssh.service - OpenBSD Secure Shell server.

Fix

The easy and quick fix will be to run:

Ubuntu Server Terminal
sudo reboot
warning

This is not recommended if you do not have physical or VNC access to the server, as you might lose access.

To fix this without rebooting, run the below commands to do a full daemon-reload:

Ubuntu Server Terminal
sudo systemctl daemon-reload
sudo systemctl restart ssh

With this, your port will be updated to the new port number. Verify with sudo systemctl status ssh and then try logging in again from a new terminal session with the new port.

caution

If the above option did not fix the issue, then try rebooting the server. Please make sure you either have physical access or VNC access.

Step 6: Update SSH Clients and Automation Scripts

If you’re using SSH clients like PuTTY or automation tools (e.g., Ansible, Jenkins), update them to use the new port.

  • In PuTTY, go to Connection > SSH and set the port to 3333.
  • For command-line scripts, add the -p 3333 flag to your SSH commands.

Optional: Security Best Practices for SSH

Changing the SSH port is only one aspect of securing your SSH access. Here are additional recommendations:

  • Disable Root Login: Modify the PermitRootLogin directive to no in sshd_config to prevent root logins.

    PermitRootLogin no
  • Use SSH Key Authentication: Disable password-based logins by setting PasswordAuthentication to no.

    PasswordAuthentication no
  • Limit User Access: Use the AllowUsers directive to specify which users can log in via SSH.

    AllowUsers user1 user2
  • Enable Two-Factor Authentication (2FA): For added security, enable 2FA using tools like Google Authenticator or Duo.

Troubleshooting

If you encounter issues after changing the SSH port, check the following:

  • Firewall Rules: Ensure that the new port is open and allowed through the firewall.

  • SSH Service Status: Verify that the SSH service is active:

    sudo systemctl status ssh
  • Syntax Errors: Mistakes in sshd_config can cause issues. Use sshd -t to check for syntax errors before restarting the SSH service.

    sudo sshd -t
  • SELinux Configurations (for SELinux-enabled systems): If you are on an SELinux system, add the new port as an allowable SSH port:

    sudo semanage port -a -t ssh_port_t -p tcp 3333
    note

    SELinux settings are typically found on CentOS and RHEL.

Conclusion

Changing the default SSH port is a straightforward yet effective method to improve your server’s security. While it may not stop determined attackers, it can help reduce the number of automated attacks and obscure your server’s SSH endpoint. Remember to combine this with other security practices, like disabling root login, enforcing key-based authentication, and configuring a firewall, for a robust SSH security setup.

By following these steps, you’re taking a proactive approach to securing your server and reducing the likelihood of unauthorized access.


Complete Video Tutorial