DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Change the SSH Port on a VPS Safely

Change a VPS SSH port safely: validate sshd, open the new firewall port first, handle Ubuntu's ssh.socket activation, test a second login, and remove port 22 last.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To change a VPS SSH port safely, add the new Port value to OpenSSH, validate the configuration, allow the new port through every firewall, apply the correct systemd unit, and test a second login before removing port 22. On Ubuntu 22.10 and newer, ssh.socket may own the listening port, so restarting only ssh.service can leave SSH on 22.

What changing the SSH port actually does

SSH normally listens for connections on TCP port 22. Changing that listener to another TCP port means clients must specify the new number, for example ssh -p 2222 user@server_ip. It changes where the daemon accepts connections; it does not change your username, keys, host keys, authentication policy, shell, or running sessions.

As an Amazon Associate I earn from qualifying purchases.

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

A nonstandard port can reduce automated scans aimed at port 22, but it is not a substitute for key-based authentication, timely updates, least-privilege accounts, or a correctly configured firewall. Treat the move as a connection and firewall change that must be staged carefully, not as a complete security control.

Before you touch SSH

Do the preparation while your current SSH session is working. Never close that session until a separate terminal has successfully logged in through the new port.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  • Have an account that can run sudo.
  • Know the VPS provider’s web, serial, or VNC console path. It is your recovery route if a firewall or systemd mistake blocks SSH.
  • Identify every firewall in front of the VM. A VPS may have both an in-guest firewall such as UFW and a provider-level firewall or security group. The new port must be allowed in each one.
  • Choose an unused high TCP port, such as 2222 or 52022. Avoid ports already used by another service and avoid well-known service ports.
  • Record the current address, username, and authentication method so the test command is unambiguous.

Know which SSH startup model your VPS uses

The correct apply step depends on the operating system and how OpenSSH is started.

Ubuntu 22.10 and later

Several Ubuntu guides report that OpenSSH is started through systemd socket activation on these releases. The ssh.socket unit owns the listening socket and starts sshd when a connection arrives. In that arrangement, changing /etc/ssh/sshd_config and restarting only ssh.service may leave a listener on port 22.

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

Guidance for Ubuntu 24.04 is inconsistent: one guide says the socket picks up the value from sshd_config automatically, while others report that the listener stayed on 22 until the socket was reloaded or overridden. Do not assume either behavior. Check the actual listener with ss after applying the change, and use the socket procedure below if 22 remains open.

Ubuntu 22.04 and older, and systems without socket activation

On these systems, the traditional procedure is to edit the SSH configuration and restart the SSH service. You should still validate the file, open the firewall first, keep your existing session open, and verify from a second terminal.

Other Linux distributions

The file and service names can differ. The OpenSSH configuration is commonly under /etc/ssh/, but confirm the service with systemctl status ssh or systemctl status sshd. On RHEL-family systems with SELinux enforcing, a new port may also require an SELinux port label using semanage; the procedure varies and is not established here, so consult that distribution’s SELinux policy documentation before switching.

Step-by-step: move an Ubuntu VPS to port 2222

The commands below use 2222 as an example. Substitute the free port you selected everywhere, and keep the old port open until the test succeeds.

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

1. Back up the SSH server configuration

Create a copy before editing:

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

If you later need to undo the edit, this backup gives you a known starting point. It does not back up firewall rules or systemd overrides, so note those changes separately.

2. Inspect the main file and drop-in directory

Ubuntu’s default file begins with an include for /etc/ssh/sshd_config.d/*.conf. OpenSSH generally uses the first value it encounters for a directive. A drop-in can therefore determine the effective port before a later Port line in the main file is read.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Search all relevant files before deciding where to make the change:

sudo grep -RIn --include='*.conf' '^[[:space:]]*Port[[:space:]]' /etc/ssh/sshd_config /etc/ssh/sshd_config.d 2>/dev/null

Read the beginning of the main file and list the drop-ins:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo sed -n '1,80p' /etc/ssh/sshd_config
sudo find /etc/ssh/sshd_config.d -maxdepth 1 -type f -name '*.conf' -print 2>/dev/null

Ensure that the first active Port directive is the one you intend to use. If an earlier drop-in sets Port 22, changing a later line may have no effect. You can edit that existing directive, remove the conflicting line, or place a deliberately named drop-in where the include order makes it the first active value. Do not leave contradictory active values and hope the last one wins.

3. Set the new port

Edit the configuration with your preferred editor:

sudo editor /etc/ssh/sshd_config

Add or change an active line to:

Port 2222

Keep the line outside a Match block. A port setting placed inside a conditional block will not behave as a global listener setting. If you prefer a separate file, create a clearly named drop-in such as /etc/ssh/sshd_config.d/99-port.conf, but first confirm that no earlier included file or main-file line supplies a different Port value.

4. Validate before restarting anything

Run OpenSSH’s syntax check:

sudo sshd -t

No output and an exit status of zero indicate that the configuration parsed successfully. A message identifies the file and line that needs correction; do not proceed until the check succeeds. This test catches syntax and structural errors, but it does not prove that the firewall allows the port or that systemd is listening there.

You can inspect the daemon’s effective settings with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo sshd -T | grep -E '^(port|listenaddress) '

Use this as a configuration check, not as a replacement for checking the actual listening socket.

5. Open the new port before switching listeners

If UFW is active, allow the new TCP port while port 22 remains permitted:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
sudo ufw allow 2222/tcp
sudo ufw status

Do this before restarting SSH. If your provider supplies a separate firewall or security-group control, add an inbound TCP rule for the same port there as well. A guest rule cannot override a provider firewall that drops the packet upstream. The exact provider interface is not standardized, so verify the rule in that control panel before testing.

UFW rule changes normally take effect immediately. If your environment specifically requires a reload, use the provider’s documented procedure; a reload is not part of the core SSH socket change.

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

6. Apply the change on Ubuntu 22.10 and newer

Reload systemd’s unit definitions, then restart the socket unit:

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

Restarting only ssh.service can leave ssh.socket bound to port 22. The socket restart is the important step when socket activation controls the listener. Keep your original connection open; an existing session can continue even if new connections are misconfigured.

7. Apply the change on systems without socket activation

On an older Ubuntu release or another system that starts the daemon directly, restart the service after sshd -t succeeds:

sudo systemctl restart ssh

If that unit does not exist, try the distribution’s daemon name:

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.
sudo systemctl restart sshd

Use systemctl status ssh or systemctl status sshd to identify the active unit rather than restarting both blindly.

8. Confirm which ports are listening

Check the kernel’s listening sockets:

sudo ss -tlnp | grep -E ':(22|2222)b'

You should see the new port. If 22 is still listed, do not remove the port-22 firewall rule. Continue with the troubleshooting section instead. If neither port is listening, inspect the service status and logs while your current session remains open.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

9. Test from a second terminal

Open a new terminal or a separate local window and connect explicitly to the new port:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ssh -p 2222 user@server_ip

Authenticate normally and run a harmless command such as whoami or hostname. Verify that the account, permissions, and expected host key are present. Keep both the original and new sessions active for a few minutes so you can detect intermittent firewall or socket problems.

10. Remove port 22 only after successful testing

Once the second login works and ss shows the intended listener, remove the old UFW rule:

sudo ufw delete allow 22/tcp
sudo ufw status

If a provider firewall or security group also allowed 22, remove that rule there after confirming the new rule works. Removing the old rule last gives you a recovery path during the risky part of the change.

When Ubuntu still listens on port 22

This is the most common symptom of applying the daemon configuration without changing the socket unit. First confirm the facts rather than making more edits:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ss -tlnp | grep -E ':(22|2222)b'
sudo systemctl status ssh.socket
sudo systemctl cat ssh.socket

If ssh.socket owns port 22, create a systemd drop-in instead of editing a file under /lib/systemd/system/. Vendor-unit edits can be overwritten by package upgrades.

Use a persistent socket override

Open an override editor:

sudo systemctl edit ssh.socket

Enter:

[Socket]
ListenStream=
ListenStream=2222

The empty ListenStream= line clears the inherited listener; the following line defines the new port. Save and exit, then apply the override:

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

Check again:

sudo ss -tlnp | grep -E ':(22|2222)b'
sudo systemctl status ssh.socket

Some guides show a direct ListenStream= assignment followed by a daemon reload, while others explicitly clear the inherited value first. Clearing it in the override makes the intended replacement explicit. Do not edit /lib/systemd/system/ssh.socket directly; an upgrade may restore the vendor version and undo your change.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

If the override editor opens an empty file

That is normal: systemd is asking for local settings layered on top of the vendor unit. Include the [Socket] section and both ListenStream lines exactly, save, reload, and restart. If systemd reports a syntax error, reopen the override and check section spelling, capitalization, and the empty assignment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting by symptom

Symptom Likely cause What to check
New connection times out The new port is blocked before it reaches sshd. Confirm the UFW rule, provider firewall or security-group rule, VPS address, and TCP port. Check sudo ufw status.
Connection is refused No process is listening on the chosen port, or the service failed after the change. Run sudo ss -tlnp, sudo systemctl status ssh, and sudo systemctl status ssh.socket. Review the service error and rerun sudo sshd -t.
Port 22 remains open ssh.socket still owns the old listener, or a drop-in supplied an earlier Port 22. Inspect systemctl cat ssh.socket and search all files under /etc/ssh/sshd_config.d/. Apply the socket override if required.
sshd -t reports an error There is a syntax, permission, include, or unsupported-directive problem. Fix the exact file and line named in the message. Do not restart SSH until the command exits successfully.
New login reaches the server but authentication fails The network path works; the username, key, agent, or authentication policy is the issue. Use the same account and key that worked on port 22. Run the client with -v for diagnostic output while keeping the original session open.
Changing the file appears to do nothing A different included file supplies the first effective Port value, or the socket was not restarted. Use the recursive grep command, inspect include order, run sshd -T, then reload and restart the correct unit.

How to roll back without losing access

If the new port fails but the original session still works, restore the known configuration and listener before experimenting further:

  1. Restore the backup if you need to discard the edit: sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config.
  2. Run sudo sshd -t and correct any error.
  3. Remove or edit the local ssh.socket override if it is forcing the wrong port. sudo systemctl revert ssh.socket removes locally generated overrides for that unit; confirm the result with systemctl cat ssh.socket.
  4. Reload systemd and restart the appropriate unit: sudo systemctl daemon-reload, followed by sudo systemctl restart ssh.socket on socket-activated systems or sudo systemctl restart ssh on traditional setups.
  5. Ensure UFW and any provider firewall allow the port you are using for recovery. Keep port 22 allowed until a working login is confirmed.

If every SSH session is gone, use the VPS provider’s console. From there, inspect sshd -t, systemd status, firewall rules, and listening sockets exactly as you would over SSH.

Port-selection and operational considerations

Choose a port that is actually free

A high number is only useful if another daemon is not already bound to it. Check current listeners before choosing:

sudo ss -tlnp

Do not select a port used by a database, control panel, monitoring agent, or custom application. If you run several VPS services, keep a written inventory so a future package or deployment does not collide with the SSH listener.

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.

Keep client configuration maintainable

After the move, every client must know the new port. You can specify it per connection with ssh -p 2222 user@server_ip or add a host entry to your local SSH client configuration:

Host my-vps
    HostName server_ip
    User user
    Port 2222

Use a neutral host alias rather than changing scripts ad hoc. Update deployment jobs, monitoring checks, backup tools, and configuration-management inventories that connect to the VPS.

Remember that existing sessions are different from new listeners

An established TCP session does not move to a new port. It can remain usable after the listener is restarted, which is why the original session is valuable during the change. New clients, however, must reach the new listener and pass every firewall layer.

What this change does not solve

Moving SSH away from 22 does not repair weak passwords, exposed private keys, excessive privileges, outdated OpenSSH packages, or an overly broad firewall. Continue to enforce the authentication and access policies appropriate for your VPS. The port move should be treated as one operational hardening measure and a configuration migration, not proof that the server is secure.

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

Final verification checklist

  • The selected port is unused and documented.
  • /etc/ssh/sshd_config and every included drop-in have one intended effective Port value.
  • sudo sshd -t completes successfully.
  • The new TCP port is allowed in UFW and in any provider firewall or security group.
  • On socket-activated Ubuntu, sudo systemctl daemon-reload and sudo systemctl restart ssh.socket have been run.
  • sudo ss -tlnp shows the new listener and no unintended listener on 22.
  • A second terminal has completed a real login using ssh -p NEW_PORT user@server_ip.
  • Only after those checks, the port-22 firewall rules are removed.

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.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
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.