October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

How to Change SSH Port in Ubuntu 24.04 or 22.04 Linux

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Changing the SSH port is a practical way to reduce noise from automated scans and misdirected traffic. It’s not real security by itself, but it pairs well with strong authentication, firewall rules, and hardened SSH settings.

This guide walks you through the full process on Ubuntu 24.04 or 22.04: editing /etc/ssh/sshd_config, adjusting firewall rules, verifying the service is listening, and testing connectivity without locking yourself out.

As an Amazon Associate I earn from qualifying purchases.

Why changing the SSH port matters (and what it won’t do)

Many bots probe common ports like 22. If you move SSH to a different port, you’ll typically see fewer connection attempts and faster logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

However, changing the port doesn’t stop determined attackers. If the server is reachable and the SSH daemon is still exposed, attackers can still find the new port through enumeration or configuration leaks.

#1 Best Overall
EZITSOL USB for Ubuntu 24.04 & 22.04 64bit,Lubuntu 18.04 32bit | 3IN1 Bootable Linux USB flash drive/Stick,Jump Drive,Pendrive,Thumb drive
  • 3-in-1: 16GB Multiboot USB flash drive for Ubuntu 24.04 LTS 64bit & 22.04 LTS 64bit, Lubuntu 18.04 LTS 32bit. All are LTS versions, namely, Long Terrm Support Version. The versions you received might be latest than above as we update them when we think necessary.
  • Compatibility: Compatible with any brand's PC, works with both legacy BIOS and UEFI booting mode, except for Apple computers, Chromebooks and ARM-based devices.
  • Popularity:Most popular linux distributions and all come with common software includes office software, web browser, image editing, multimedia, and email except Lubuntu which is desgined to targted for very old PC.
  • Support: Print user guide and support available. please contact us for help if you have an issue.
  • Live USB or install: You can either try on USB or install on hard drive.

Prerequisites and safety checklist

  • You’re on Ubuntu 24.04 or 22.04 with root (or sudo) access.
  • You have an active session (SSH or console) you can keep running while you test.
  • You know whether you use UFW (ufw) or rely on raw firewall rules.
  • You can access the SSH config file: /etc/ssh/sshd_config.
  • You know the service name: on Ubuntu it’s typically ssh.

Safety rule: Always keep an existing session open until you’ve confirmed you can log in on the new port.

Decide the new port

Pick a port that isn’t already in use. Common choices are high ports like 2222 or 22000. Avoid privileged ports below 1024 unless you have a specific reason.

Check what’s already listening:

  1. sudo ss -ltnp | grep -E ':(22|2222|22000)\b'
  2. If you chose a custom port, replace the values accordingly.

For example, if 2222 is free, you can proceed.

Update SSH configuration (sshd_config)

The SSH daemon reads its configuration from /etc/ssh/sshd_config and may also include other files. On Ubuntu, sshd_config typically already contains Port 22 or a comment that implies it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Edit the SSH config file

  1. sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
  2. sudo nano /etc/ssh/sshd_config

Find the Port directive. It might look like:

#Port 22

Change it (or add a new line) so it sets your new port. For example, to use 2222, set:

Port 2222

Check for multiple Port directives

If multiple Port lines exist (including in included files), you can end up with unexpected behavior. Keep it simple: use a single explicit Port directive in the effective configuration.

To confirm where Port is set, you can run:

  1. sudo grep -nE '^\s*Port\s+' /etc/ssh/sshd_config
  2. If you use included config fragments, also check them (example patterns): /etc/ssh/sshd_config.d/ on some systems, though it’s not always present on Ubuntu by default.

Validate SSH config before restarting

Ubuntu ships sshd with a built-in config check.

  1. sudo sshd -t

If there’s no output, the config is syntactically valid.

Restart or reload SSH safely

Use restart after changing the listening port:

  1. sudo systemctl restart ssh

If you prefer a shorter window with less disruption, you can use reload for some SSH settings, but for port changes a restart is the reliable choice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Adjust the firewall to allow the new SSH port

If a firewall blocks inbound traffic to the new port, you’ll lose access. Update firewall rules before (or immediately after) restarting SSH, and keep your existing session alive.

Firewall option A: UFW (ufw)

First check whether UFW is active:

  1. sudo ufw status verbose

If it’s active, allow the new port (example 2222):

  1. sudo ufw allow 2222/tcp

Then decide whether to keep or remove the old rule. If you want to fully switch away from 22:

  1. sudo ufw delete allow 22/tcp
  2. sudo ufw reload

To verify rules:

  1. sudo ufw status

Firewall option B: nftables (common on modern Ubuntu setups)

Check whether nftables is in use:

  1. sudo nft list ruleset | head -n 20

Look for rules that allow TCP port 22. You’ll need to add a rule for your new port (example 2222) and optionally remove or narrow the rule for 22.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Because nftables rule sets vary by how you installed/managed them, don’t blindly paste commands. Instead, identify the specific chain/rules that handle inbound TCP and update them with the new port, keeping the same interface and source restrictions.

Firewall option C: iptables (legacy or compatibility setups)

Check current rules:

  1. sudo iptables -S

If you see rules allowing TCP/22 to the host, mirror them for your new port:

  • Add an accept rule for TCP new-port (e.g., 2222).
  • Optionally remove the accept rule for TCP 22 after you’ve confirmed connectivity.

Be cautious if you use both IPv4 and IPv6 rules. You may need to check ip6tables as well.

Verify SSH is listening on the new port

Once SSH is restarted, confirm it’s bound to the new port.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check listening sockets

  1. sudo ss -ltnp | grep -E ':2222\b'

You should see a LISTEN entry with process sshd.

Check service status

  1. systemctl status ssh --no-pager -l

If there’s a configuration error, SSH may fail to start or refuse to reload.

Review logs if needed

  1. sudo journalctl -u ssh -n 100 --no-pager

Look for lines mentioning sshd, configuration, error, or Server listening on.

Test remote access and avoid lockouts

This is where you prove the change before you remove access to port 22.

From your client: specify the new port

On your local machine, use:

  1. ssh -p 2222 <username>@<server-ip>

For key-based auth, ensure your key is still authorized for that user. Port changes don’t alter keys, but they can change which rules allow traffic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify firewall behavior from outside

Testing from the same machine that has local access can hide firewall misconfigurations. If possible, test from a different network (e.g., mobile hotspot) to confirm the public firewall path works.

Update clients and connection workflows

If you connect often, set up a permanent shortcut so you don’t forget the port.

Rank #2
Ubuntu Linux 24.04 LTS Bootable Live USB Flash Drive
  • Ubuntu Linux 24.04 LTS Features: Security features to detect threats, including malware, viruses, and ransomware protection capabilities built into the operating system
  • Data Protection and Network Security: Full-disk encryption to protect your data and privacy, configurable firewall to control incoming and outgoing network traffic, and support for Secure Boot to ensure that your system boots securely
  • Enhanced Performance and Speed: Improved boot times to get you up and running quickly, enhanced performance and responsiveness with faster app loading and switching, and efficient resource management to maximize system performance
  • Latest Software Packages Included: Includes the latest versions of popular software applications such as LibreOffice office suite, Firefox web browser, Thunderbird email client, and VLC media player
  • Wide Hardware Compatibility: Compatible with a wide range of hardware configurations including UEFI and Secure Boot, USB 3.0 connectivity, SATA and NVMe storage devices, and graphics cards from major manufacturers

SSH config on your client (recommended)

Edit your local SSH config:

  1. nano ~/.ssh/config

Add a host entry:

Host ubuntu-prod HostName <server-ip-or-dns> User <username> Port 2222

Then connect with:

  1. ssh ubuntu-prod

Remember host key prompts

If you connect from a new client, you may see a host authenticity prompt. That’s normal. If the server’s host key changed unexpectedly, investigate before accepting.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Optional hardening after changing the port

Once you’ve moved off port 22, it’s smart to reduce brute-force and improve resilience.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Restrict by source IP (if you can)

In SSH config, you can restrict users or networks using directives like AllowUsers and AllowGroups. For IP-level restrictions, the firewall is usually the cleanest place to do it, but SSH also supports access controls.

Use key-based auth and disable password login

In /etc/ssh/sshd_config, consider:

  • PasswordAuthentication no
  • PubkeyAuthentication yes

After edits: run sudo sshd -t, then sudo systemctl restart ssh.

Set a sane idle timeout

Optionally add:

  • ClientAliveInterval 300
  • ClientAliveCountMax 2

This helps drop dead sessions without user intervention.

Troubleshooting when SSH stops working

If you changed the port and now can’t connect, work through this in order. Don’t guess.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1) Confirm SSH is running

  1. sudo systemctl status ssh --no-pager

If it’s not running, view logs:

  1. sudo journalctl -u ssh -n 200 --no-pager

2) Confirm the daemon is listening on the new port

  1. sudo ss -ltnp | grep -E ':2222\b'

If it’s not listening, the Port directive may not have been applied (wrong file, conflicting config, or a restart didn’t take).

3) Confirm you updated the correct configuration file

On Ubuntu, the effective config is usually /etc/ssh/sshd_config. But included fragments can override settings. Search for Port directives across files you’re using.

  1. sudo grep -RIn '^\s*Port\s+' /etc/ssh/

Look for duplicates.

4) Firewall still allows 22 but blocks 2222

Common failure mode: you restarted SSH and changed the config, but forgot to allow the new port in UFW (or nftables/iptables).

For UFW, run:

  1. sudo ufw status numbered

Ensure there’s an allow rule for 2222/tcp and remove/adjust 22 only after successful testing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5) You edited but didn’t restart SSH

Editing config alone won’t change runtime behavior. Ensure you ran:

  1. sudo systemctl restart ssh

6) SELinux/AppArmor is blocking (less common on Ubuntu)

Ubuntu commonly uses AppArmor profiles. It’s not typical for SSH port binding to be blocked just because of a custom port, but check for denials if you see repeated failures.

  1. sudo dmesg | tail -n 50
  2. sudo journalctl -k -n 100 --no-pager

Rollback plan if you need to revert quickly

Have a plan before you change anything. If you lose access, use console access, cloud console, or out-of-band management if available.

Rollback to port 22

  1. Open SSH config: sudo nano /etc/ssh/sshd_config
  2. Set: Port 22
  3. Validate: sudo sshd -t
  4. Restart: sudo systemctl restart ssh

Restore firewall rules

If you used UFW, allow 22/tcp again and remove the 2222/tcp rule after confirming access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. sudo ufw allow 22/tcp
  2. sudo ufw delete allow 2222/tcp
  3. sudo ufw reload

FAQs

Do I need to change the SSH port on both server and client?

Yes. The server listens on the new port. Your client must connect using ssh -p <port> or an SSH config entry with Port <port>.

Can I keep port 22 open and also add a new port?

SSH can listen on multiple ports if you configure multiple Port directives. In sshd_config, clarity matters—use only what you intend to support. For reduced exposure, many admins switch fully and then remove the old firewall rule.

Will this affect existing SSH sessions?

Existing connections typically continue until they naturally end, but restarting SSH can disrupt active sessions depending on how the service is restarted and your environment. That’s why keeping an existing session open during the change is important.

What if sudo sshd -t passes but connections still fail?

Most often it’s the firewall, a wrong port number, or the daemon isn’t actually bound to the expected port. Check ss -ltnp and confirm your client is targeting the new port.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is changing the port enough to stop brute-force attacks?

No. It reduces opportunistic scanning, but brute-force can still happen. Use key-based authentication, disable password login if possible, and restrict by IP or network using firewall rules.

Bottom Line

To change the SSH port on Ubuntu 24.04 or 22.04, update /etc/ssh/sshd_config, validate with sudo sshd -t, restart SSH, then immediately align your firewall so inbound traffic reaches the new port.

Test connectivity from outside your network, keep port 22 enabled until you confirm everything works, and treat port changes as a noise-reduction step—not a complete security solution.

Quick Recap

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.