Skip to main content
+44 7575 472931[email protected]
HostaccentKnowledge BaseHosting, websites, SEO, and growth

How to Change SSH Port Without Locking Yourself Out (2026)

How to change SSH port without locking yourself out: edit sshd_config, fix the Ubuntu ssh.socket trap, open the firewall, then test before closing port 22.

VPSSecurityBeginner Guide
How to change SSH port safely: sshd_config edit, firewall rule and the Ubuntu ssh.socket fix, tested in 2026

Leave a fresh server on port 22 for an hour and check /var/log/auth.log. You will find hundreds of login attempts from scanners that found your IP within minutes of it going live. None of them know your password. All of them are trying anyway.

Moving the SSH daemon to a different port silences most of that noise in about five minutes. This guide covers how to change SSH port settings on Ubuntu, Debian and RHEL-based servers, including the one step that most tutorials written before 2023 get badly wrong.

Quick Answer: Set Port 2222 in /etc/ssh/sshd_config, allow the port in your firewall with sudo ufw allow 2222/tcp, validate the file using sudo sshd -t, then restart SSH. On Ubuntu 22.10 and newer you must also run sudo systemctl daemon-reload && sudo systemctl restart ssh.socket, or the server keeps listening on 22. Test the new port in a second terminal before you close the old one.

Our engineers work through 20-30 client server issues every day, and self-inflicted SSH lockouts are a regular guest in that queue. Hostaccent has been hosting since 2016 and UK-incorporated since 2018, and the steps below, current as of September 2026, are what we actually run on production boxes rather than a tidied-up copy of the vendor manual.

Rule Zero: Never Close the Terminal You Are Working In

Keep your existing SSH session open until the new port is proven. That is the entire article in one sentence, and it is the step people skip.

Here is why it matters. Every other mistake in this process is recoverable while you still have a shell. A typo in sshd_config, a firewall rule pointing at the wrong protocol, a SELinux policy that silently blocks the bind: all of it takes thirty seconds to undo from an open session. Close that session first and the same typo becomes a support ticket, a rescue console, or a rebuild.

So before you edit anything, open a second terminal window and connect to the server again on port 22. You now have a working session and a spare. Do the editing in one, test in the other, and do not close either until ssh -p 2222 succeeds from a completely new connection.

One detail people miss: an established SSH session survives a daemon restart. Restarting the service only affects new connections, so your open shell keeps working even if the config you just wrote is broken. That is a safety net, and it is also a trap, because a session that still works tells you nothing about whether anyone else can get in. Your open terminal proves the past. Only a fresh connection proves the present.

Back up the config file first as well:

bash
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Then confirm you have out-of-band access. Most VPS control panels ship a browser console (noVNC, serial console, or a rescue boot) that bypasses SSH entirely. Find that button now, while you can still log in, rather than at 2am while you cannot. If your provider does not offer console access, that is worth knowing before you start hardening anything.

Pro Tip: On a server you genuinely cannot afford to lose, schedule an automatic rollback before you restart the daemon: echo "cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config && systemctl restart ssh" | sudo at now + 10 minutes. If your test connection works, cancel the job with sudo atrm <job-id>. If it does not, the server undoes your change by itself in ten minutes. We use this pattern on any remote box without a reliable console.

How to Change SSH Port in Seven Steps

The full sequence takes about five minutes on a standard Ubuntu 24.04 or AlmaLinux 9 VPS. Order matters: the firewall opens before the daemon moves, never after.

1. Pick a port. Anything from 1024 to 65535 that is not already in use. Ports below 1024 are reserved for system services and require root to bind. Avoid the obvious decoys (2222, 22222, 2200) since scanners check those next, and avoid ports your stack already uses: 3306 for MariaDB, 6379 for Redis, 8080 for proxies.

| Port range | Use for SSH? | Why | |---|---|---| | 1-1023 | No | Reserved system ports, conflicts with known services | | 1024-49151 | Careful | Registered ports; check nothing else claims it | | 49152-65535 | Best choice | Dynamic/private range, rarely scanned wholesale | | 2222 / 22222 | Avoid | First two guesses in every scanner's fallback list |

Check the port is free before you commit to it:

bash
sudo ss -tlnp | grep :52022

Empty output means nothing is listening there.

2. Edit the config. On Ubuntu, the cleanest method is a drop-in snippet rather than the main file:

bash
sudo nano /etc/ssh/sshd_config.d/99-port.conf

Add one line: Port 52022. This matters more than it looks. Ubuntu's default sshd_config opens with Include /etc/ssh/sshd_config.d/*.conf at the very top, and OpenSSH uses the first value it finds for most directives, so a stray snippet in that directory quietly beats whatever you type in the main file. If your sshd_config port change appears to do nothing, check that directory before you check anything else. The full directive list lives in the OpenSSH sshd_config manual.

3. Validate before restarting. This single command has saved more servers than any other line in this guide:

bash
sudo sshd -t

Silence means the file parses. Any output means stop and fix it, because restarting on a broken config leaves the daemon dead and you locked out.

4. Open the firewall on the new port while leaving 22 open. Both stay open until testing finishes.

5. Restart the service. sudo systemctl restart ssh on Debian and Ubuntu, sudo systemctl restart sshd on RHEL, AlmaLinux and Rocky. Ubuntu 22.10 and newer need an extra step covered in the next section.

6. Confirm the daemon actually moved:

bash
sudo ss -tlnp | grep sshd

You want to see your new port in the output. If it still says 0.0.0.0:22, the change did not apply.

7. Test from a new terminal, then close port 22. Details on both below. Ubuntu's own OpenSSH server documentation covers the surrounding configuration options if you want to harden further in the same pass.

Why Editing sshd_config Does Nothing on Ubuntu 22.10 and Newer

This is the section most guides are missing, and it is the number one reason people think the port change failed.

Since Ubuntu 22.10, OpenSSH ships with systemd socket activation enabled by default. Instead of sshd sitting in memory holding port 22, a systemd unit called ssh.socket owns the listener and spawns sshd only when a connection arrives. It saves a few megabytes of RAM on small instances. It also means the Port directive in your config file is not what decides the listening port, because systemd already bound the socket before sshd was ever consulted.

So you edit the file, restart the service, run ss -tlnp, and see port 22 staring back at you. The config is correct. The server is simply not reading it for that setting.

You have two clean fixes. The first keeps socket activation and configures it properly with a drop-in:

bash
sudo mkdir -p /etc/systemd/system/ssh.socket.d
sudo nano /etc/systemd/system/ssh.socket.d/listen.conf
ini
[Socket]
ListenStream=
ListenStream=52022

That empty ListenStream= line is not a typo, and leaving it out is the classic follow-up mistake. Systemd appends to list-type directives rather than replacing them, so without the blank reset your server listens on 22 and 52022, which defeats the whole exercise. Apply it with:

bash
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

The second option turns socket activation off and returns to the traditional persistent daemon, which is what we prefer on servers running fail2ban and per-connection rate limits:

bash
sudo systemctl disable --now ssh.socket
sudo systemctl enable --now ssh.service

After that, sshd_config behaves exactly as every older tutorial describes. On the self-managed Ubuntu fleet Hostaccent runs behind Cloudflare and Nginx, this is the default we standardise on, because a persistent daemon gives fail2ban a stable process to watch and makes connection logging far easier to reason about. The systemd.socket manual documents the override syntax in full.

One more wrinkle if you upgraded rather than installed fresh. When Ubuntu 22.04 machines move to a socket-activated release, any existing Port or ListenAddress setting gets migrated into a generated file at /etc/systemd/system/ssh.socket.d/addresses.conf. Read that file before you write your own drop-in, or you will spend an afternoon debugging a port you set two years ago.

Insider Insight: Debian 12, AlmaLinux 9, Rocky 9 and CentOS Stream are unaffected. This is an Ubuntu packaging decision, not an upstream OpenSSH one, so a guide that works perfectly on a Debian droplet can fail completely on Ubuntu 24.04. If you manage a mixed fleet, check systemctl is-enabled ssh.socket before you touch anything.

Professional help available

Still working through this server issue?

Send the symptoms, error output, and what you have already tried. We can work with Hostaccent services or infrastructure hosted with another provider.

Request server helpHow server support worksHosted elsewhere? One-time paid support is available after scope and price confirmation.

Firewall, SELinux and Fail2ban: What Actually Blocks the New Port

Three separate layers can refuse your connection after a perfectly correct config edit, and each fails in a different way. Work through them in order.

The host firewall

On Ubuntu and Debian with UFW:

bash
sudo ufw allow 52022/tcp comment 'SSH custom port'
sudo ufw status numbered

On AlmaLinux, Rocky or RHEL with firewalld:

bash
sudo firewall-cmd --permanent --add-port=52022/tcp
sudo firewall-cmd --reload

Running CSF, as many cPanel and WHM servers do? Add the port to TCP_IN and TCP_OUT in /etc/csf/csf.conf, then run csf -r. Forgetting the CSF file while UFW sits inactive is a common cause of the "I opened it and it still refuses" ticket. Check which firewall is actually in charge before you edit one, because a server running both CSF and UFW will happily accept rules in the inactive tool and apply none of them.

Add the new rule while port 22 is still allowed. If you swap the rules in a single step and the daemon has not moved yet, you cut yourself off from a server that is working perfectly.

The network firewall you forgot about

Your server's own firewall is only the inner door. Cloud security groups, provider-level firewalls and hardware ACLs all sit in front of it, and none of them care what UFW says. If the connection times out rather than returning "connection refused", suspect this layer first: a refusal means something answered, a timeout means nothing did.

SELinux

On RHEL-family systems with SELinux enforcing, the daemon is not allowed to bind an arbitrary port. The SELinux SSH port change is one command, and skipping it produces a bind failure in the journal that looks nothing like a permissions problem:

bash
sudo semanage port -a -t ssh_port_t -p tcp 52022

If semanage is missing, install policycoreutils-python-utils first. Verify with sudo semanage port -l | grep ssh.

Fail2ban and rate limiting

Fail2ban watches a port, not a service name. After the move, update the sshd jail in /etc/fail2ban/jail.local with port = 52022 and reload, or you have quietly disabled your brute-force protection at exactly the moment you thought you were hardening the box. The same applies to any Nginx or edge rate-limit rules keyed to SSH traffic; our guide to Nginx rate limiting for basic DDoS and bot protection covers the equivalent patterns on the web tier, and the complete 2026 VPS hardening checklist puts all of these layers in sequence.

Test New SSH Port Before Closing the Old One

Test new SSH port before closing port 22. Not after. This is where the two-terminal discipline pays off, and it takes under a minute.

From your local machine, in a brand new terminal:

bash
ssh -p 52022 user@your-server-ip

If that lands you at a prompt, you are done with the risky part. If it hangs or refuses, go back to your still-open original session and work through the three layers above. Read the error carefully first, because the wording narrows it down immediately: "connection refused" means you reached the server and nothing was listening, while a timeout means your packets never got there at all.

We run what our team calls the Three-Door Check, because a failed SSH connection is always one of exactly three doors being shut, and testing them in order takes about 60 seconds:

  1. Door one, the daemon. sudo ss -tlnp | grep sshd on the server. If your port is not listed, the problem is sshd_config or ssh.socket, and nothing else matters yet.
  2. Door two, the host firewall. sudo ufw status or sudo firewall-cmd --list-ports. If the port is missing here, you get a timeout from outside and a working ssh -p 52022 localhost from inside. That split is the fingerprint.
  3. Door three, the network. Test from a machine outside the datacenter with nc -vz your-server-ip 52022. A timeout with doors one and two confirmed green means a cloud security group or upstream ACL.

Across the 4,000+ site migrations Hostaccent has handled, the door that catches people most often is the third one, because the server itself reports everything as healthy. Nothing in the logs is wrong. The packets simply never arrive.

Once the new port works, close the old one:

bash
sudo ufw delete allow 22/tcp

Then update everything else that assumed port 22. Backup jobs, deploy pipelines, Git remotes, monitoring agents and SFTP clients all break silently at 3am otherwise. The friendliest fix is a local ~/.ssh/config entry so you never type the flag again:

bash
Host myserver
    HostName 203.0.113.10
    Port 52022
    User deploy

Remember the syntax quirk while you are updating scripts: ssh uses a lowercase -p for ports, scp uses an uppercase -P, and rsync needs the whole thing wrapped: rsync -avz -e "ssh -p 52022". If your automation starts failing authentication after the move, our walkthrough on FTP 530 login authentication failed errors covers the same class of credential and port mismatches on the transfer side.

Does Moving SSH Off Port 22 Actually Make You Safer?

Honestly? Less than the security blogs imply, and more than the purists admit.

Changing the port is obscurity, not security. It stops nothing that is aimed at you specifically. A determined attacker runs nmap -p- against your IP and finds the new port in a couple of minutes, and the SSH banner tells them exactly what they found. Anyone claiming a port change hardens your server against targeted attacks is selling something.

What it does do is remove you from the untargeted flood, and that is worth more than it sounds. Industry reports on internet-facing honeypots consistently show the overwhelming majority of SSH login attempts arriving on port 22 alone, with drops of well over 90% in logged attempts after moving to a high port. Fewer attempts means smaller logs, less CPU burned on failed handshakes, cleaner fail2ban data, and genuine signal when something does show up in your auth log.

Treat it as noise reduction that buys you better visibility. The controls that actually stop intrusions are the boring ones:

  • Key-only authentication. PasswordAuthentication no in sshd_config ends password brute-forcing permanently. Do this before you worry about ports.
  • PermitRootLogin no. Force a named user plus sudo, so you get an audit trail.
  • Fail2ban or CSF/LFD with sensible ban times, pointed at the correct port.
  • An IP allowlist where your team has static addresses. Nothing beats a firewall that only answers three IPs.

Our Linux VPS security baseline for Ubuntu 24.04 walks through all four in about half an hour, and if you are already under active pressure, stopping a DDoS attack in the first 10 minutes is the more urgent read. For background on how the protocol authenticates in the first place, Cloudflare's explainer on the SSH protocol is a solid primer.

Do I actually need to change the SSH port on a small VPS?

If you already have key-only login and a firewall, the port change is optional and mostly cosmetic. If you are running password authentication, change the port today and then fix the authentication, because the port move buys you quiet hours to do the real work in. One caveat worth knowing: some corporate networks and hotel Wi-Fi block outbound traffic on unusual high ports, so a port that works from your desk may fail from a client site. Port 443 is a popular workaround for exactly that reason, provided nothing else needs it.

Three things to take away:

  1. The keep-a-session-open rule prevents almost every lockout in this process.
  2. On Ubuntu 22.10+, ssh.socket decides the port, not sshd_config.
  3. Open the firewall first, test second, close port 22 last.

Your Next Step: A Server Where You Own the Root Shell

Now that you know how to change SSH port settings safely, the real question is whether your host lets you finish the job when it goes sideways. Plenty of cheap plans hand you root and nothing else. Our Linux VPS plans give you full root access, free 30 Gbps DDoS protection, a 99.99% uptime guarantee, and 24/7 support from Hostaccent's own in-house engineers rather than a script-reading queue. One honest caveat: no VPS at this price includes a cPanel or Plesk licence, since a licence costs more per month than the server, so budget separately if you need a panel. If that suits you, start on the Basic plan at $7.99/mo, renewing at the same $7.99/mo, with 30 days to change your mind.

Frequently Asked Questions About Changing the SSH Port

What is the best port to use instead of 22?

Pick something in the 49152-65535 dynamic range, such as 52022 or 61022. Scanners that bother probing beyond port 22 usually try 2222, 22222 and 2200 first, so those save you nothing. Confirm the port is unused with sudo ss -tlnp before committing, and avoid anything your stack already needs, like 3306 for MariaDB or 6379 for Redis. If you connect from restrictive corporate networks, port 443 is a practical alternative that firewalls rarely block.

How to change SSH port without rebooting the server?

You never need a reboot for this. Editing the config and restarting the SSH service applies the change immediately, and your existing connections stay alive, because a restart only affects new sessions. On Ubuntu 22.10 and newer, run sudo systemctl daemon-reload followed by sudo systemctl restart ssh.socket instead of restarting the service on its own. Always run sudo sshd -t before any restart: a syntax error plus a restart is exactly how a working server becomes an unreachable one.

Will changing the SSH port break my backups, scripts or Git access?

Yes. Anything that assumed port 22 fails the moment you close it, usually at the least convenient hour of the night. Update SFTP clients, rsync jobs, deployment pipelines, monitoring agents, cron scripts and any Git remotes using SSH URLs. Remember that ssh takes a lowercase -p while scp takes an uppercase -P, and rsync needs -e "ssh -p 52022". A ~/.ssh/config entry with the port baked in saves you from remembering any of that.

What do I do if I get locked out after changing the SSH port?

Use your provider's browser console or rescue mode, which bypasses SSH entirely, then restore the backup config and restart the daemon. This is the most common lockout ticket Hostaccent engineers see, and it is nearly always fixed in minutes once console access exists. If your host offers no console, your only route is a support ticket, which is exactly why you check for that button before making the change rather than after.

Does changing the SSH port stop brute-force attacks?

It stops the untargeted ones, which is most of the volume you see. Automated scanners sweep port 22 across entire IP ranges, so moving off it removes you from that sweep and cuts logged login attempts dramatically. It does not stop anyone targeting your server specifically, because a full port scan reveals the new port within minutes. Treat it as noise reduction, and rely on key-only authentication and fail2ban for actual protection.

Do I still need to change the SSH port if I use SSH keys?

Not strictly. With PasswordAuthentication no and key-only login, brute-force attempts against your server cannot succeed regardless of which port they hit. The remaining benefit is operational: quieter logs, lower CPU waste on failed handshakes, and real signal when a genuine anomaly appears in auth.log. Many administrators keep port 22 open with keys enforced and sleep perfectly well. If you want both, do keys first and the port second.

Can I run SSH on two ports at once during the migration?

Yes, and it is the safest way to transition a server with many users. Add a second Port line in sshd_config, or a second ListenStream= entry in your ssh.socket drop-in, and the daemon listens on both. Open both in the firewall, give your team a week to update their configs and scripts, then remove the old entry and the old firewall rule. Just remember to reload fail2ban so both ports stay monitored.

Professional help available

Still not resolved? Let a server specialist take it from here.

Send the symptoms, error output, and what you have already tried. We can work with Hostaccent services or infrastructure hosted with another provider.

  • No hosting transfer required
  • Scope confirmed before paid work
  • No changes before your approval
Request server helpHow server support worksHosted elsewhere? One-time paid support is available after scope and price confirmation.
Reviewed by

Hostaccent Editorial Team

Reviewed for technical accuracy and clarity before publication.

Last updated

Sep 18, 2026

HostAccent Editorial Team publishes practical hosting guides, operations checklists, and SEO-focused tutorials for businesses building international web presence.

Discussion

Have a question or tip about this topic? Share it below — your comment will appear after review.

Your email stays private and is only used for moderation.

Write for the Community

Have a tutorial, tip, or insight to share? Get published on the Hostaccent Blog with your name, bio, and website link.

Become a Contributor

Need a faster setup for this workflow?