CH-J Toolsserver management over SSH
Menu
All guides and articles →

How to change SSH port 22 without losing access to the server

Add a new SSH port next to the original one, verify the firewall and actual listening, and only then remove port 22. Including socket activation and SELinux.

What changing the port solves and what not to expect from it

Moving SSH from port 22 can reduce the amount of automated scanning in the log. However, it alone will not secure a weak account and will not replace updated OpenSSH, keys, or access restrictions. A new public port can be discovered. The point of this procedure is to make a managed operational change where access remains authenticated and there is a way back.

The most common cause of access loss is not a typo in the number, but an overlooked layer: provider security policy, NAT, IPv6, SELinux, or the ssh.socket unit. Therefore, first find out the real path from the client to the server. If the public port is translated to another internal port, note both values. The client connects to the public port, sshd listens on the internal one.

The examples use the new TCP port 2222 and an administrator account. This is not a universally recommended number; verify its availability, organizational policies, and that it is not already in use by another service. For a managed cluster, consider automation, monitoring, backup, and connection inventory. A successful manual login by one administrator will not verify all of these clients.

Prepare the console and map the existing configuration

Before you start changing the listener or firewall, test the provider or hypervisor console. Leave the open SSH session running and prepare a new terminal next to it for testing. The long original session can continue even when the new connections no longer work. So after the change, it is not enough to type a command in the old window.

sudo /usr/sbin/sshd -t
sudo /usr/sbin/sshd -T | grep -E "^(port|listenaddress) "
sudo ss -lntp
sudo systemctl status ssh.service ssh.socket --no-pager
sudo systemctl cat ssh.service ssh.socket

On RHEL and related systems, there is usually a unit called sshd.service. A missing ssh.socket is not a problem in itself; what matters is whether the particular installation is using it. Also check the cat output for local drop-in files and ExecStart parameters. Options passed to the daemon on the command line can change the meaning of the configuration in the file.

Back up the file you are editing, preserving ownership and permissions, to a private directory. List your current firewall permissions, port forwarding, and related Fail2ban actions. The restore is intended to revert your specific change; it should not overwrite more recent changes made by another administrator or revert the old security settings of the entire server.

First, prepare a network path for the new port

The new port must be passable before you can forward clients to it. If your server is using UFW and you are managing it from a fixed address, adding a targeted rule might look like this. Use the actual source address and the actual internal port. The documentation address in the example is not your address.

sudo ufw allow from 203.0.113.10 to any port 2222 proto tcp
sudo ufw status numbered

Do not enable inactive UFW as a side step without checking other services. For a system with firewalld or directly managed nftables, use its established procedure and do not add a second firewall manager. Also check cloud security groups and router. If the server has public IPv6, check its separate rules; IPv4 NAT does not say anything about IPv6 availability.

Do not remove the original port 22 permission yet. The transition period with two allowed ports is intended to allow for true new sign-ins and gradual client migration. If your organization requires restrictions on the VPN or management network, enforce the same restrictions on the new port. The temporary change is not intended to create broader access than the previous state.

Add a new port next to the original one

Multiple Port directives can be declared for a normally running OpenSSH daemon. Intentionally prepare both the old and new ports at the same time. Verify Include and all ListenAddress, especially if they have their own port numbers. If a specific listening address is bound to a port, simply adding a generic Port directive may not create all the intended listeners.

# Záměrný přechodný stav v načítané konfiguraci sshd:
Port 22
Port 2222

# Kontrola před aplikací:
sudo /usr/sbin/sshd -t
sudo /usr/sbin/sshd -T | grep -E "^(port|listenaddress) "

If the listener is managed directly by ssh.service, use a managed reload of this service after a successful check and check ss. On a system with sshd.service, change the unit name. The sshd -t command does not check the cloud firewall or guarantee that the new port is not occupied. Therefore, a real listener and a new login are necessary as additional checks.

# Pouze pro instalaci, kde listener spravuje tato služba:
sudo systemctl reload ssh.service
sudo ss -lntp

For an active ssh.socket, follow the next section. Reloading the daemon is not a universal way to change the ports held by systemd.

Ubuntu with ssh.socket: respect the real owner of the socket

Some Ubuntu installations use socket activation and the TCP port is held by systemd. The way Port and ListenAddress are retrieved varies between package versions. Ubuntu 24.04 introduced a generator that converts the settings into a socket configuration. Older migrated installations may have their own addresses.conf or other drop-in, so it is not enough to decide based on the distribution name alone.

sudo systemctl cat ssh.socket
sudo systemctl show ssh.socket -p Listen
sudo systemctl list-sockets --all | grep ssh
sudo ss -lntp

In a generator-driven installation, daemon-reload is used after changing the input configuration and the listener is recreated accordingly. If the configuration is held by an explicit ListenStream in a local drop-in, you must modify that source. Multiple ListenStreams can be added; an empty directive resets the list. Therefore, read the entire merged unit before applying and verify that it preserves both transient ports.

# Až po ověření zdroje socketové konfigurace a připravení obou portů:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo systemctl status ssh.socket ssh.service --no-pager
sudo ss -lntp

Depending on the bindings of the specific unit and the running daemon, a controlled restart of the service may also be required. Perform such a step with a verified console and according to the documentation of the installed package. If ss does not show the expected status, stop the migration and explain the discrepancy. Do not recklessly switch the entire system from socket activation to another operating model just because of a port change.

SELinux: allow port to service policy

On systems with SELinux, a properly written configuration may fail because the service is not allowed to bind to the given port. Check the SELinux status and existing assignments. Disabling SELinux is not a necessary part of changing the SSH port and would hide the real cause.

getenforce
sudo semanage port -l | grep ssh_port_t
# Pokud je 2222 dosud volný a nepřiřazený jinému typu:
sudo semanage port -a -t ssh_port_t -p tcp 2222

The semanage command may require a separate distribution package. If it reports that a port already exists under a different type, do not automatically change the type. Verify which service needs the assignment, or choose another suitable port. Then check the service status, auditing, and actual listening. Firewall and SELinux are separate layers: enabling one does not override enabling the other.

New login and migration of all clients

In another terminal, open a real new connection to the new port. Verify the server identity, account, and sudo if necessary. For a non-standard port, the client may register the host key under a different name; therefore, do not click the first query without comparing the trusted fingerprint. Port movement itself does not change the identity of the server key.

ssh -p 2222 spravce@server.example
sftp -P 2222 spravce@server.example

# Cílený profil OpenSSH v ~/.ssh/config:
Host muj-server
    HostName server.example
    User spravce
    Port 2222

Lowercase -pu ssh and uppercase -P in sftp are not interchangeable. Also update the profile in CH-J Tools, backup tasks, automation, monitoring and bastion settings. Check the Fail2ban action: failure logging can work even if the blocking rule still only points to the old port. Test IPv4 and IPv6 and allowed access networks as needed.

Only after successful testing, remove the original port from its actual configuration source, re-run the check and apply. Then remove the precisely identified original network permission or NAT rule. Closing the port in the firewall does not mean that the service has stopped listening; verify both. Only close the first original session after the new login is complete and the change has been recorded.

Return in case of problem and final verification

If it fails, keep the old port and rule, revert the specific change, and check the syntax. If you have already removed the old listener, use the original session or console that is open. Do not try to fix it by restarting all network services; you could lose the last working path. Distinguish between missing listener, active denial, network timeout, and key verification error.

  • The new port is demonstrably served by the expected service.
  • Both the new SSH and SFTP logins work with the correct account and key.
  • The intended network restriction applies regardless of the requested address families.
  • The original port is only removed when all dependent tasks have been converted.
  • The documentation and connection inventory correspond to the new condition and include the return procedure.

A successful change is only complete when the new state is reflected in the normal operational tools. Otherwise, the administrator opens the connection today, but a nightly backup or restore from another network fails later. A short transition period with both ports allows these dependencies to be discovered without unnecessary management downtime.

Frequently asked questions

Will changing the port secure a weak password?

No. It changes the reachable service number and can reduce the noise of regular scanners, but it does not replace strong authentication and updates.

Why does SSH keep listening on 22 after changing Port?

The listener can hold an ssh.socket, an explicit ListenAddress, a local drop-in, or another process. Check ss and systemd merged units.

Can I close port 22 first?

It is safer to first prepare a new port, prove the new login, and transfer the clients. Leave the original access as a fallback path.

Do I need to change the server SSH keys?

Changing the port itself does not require changing the server keys. Verify any new client query by comparing the trusted fingerprint.

Detailed documentation

OpenSSH: Port and ListenAddress →

Ubuntu: OpenSSH socket activation and version differences →

Ubuntu: firewall management →

systemd: socket unit configuration →

OpenSSH: SFTP client and port selection →

Biometric unlock and security →

All tutorials by category →