Running the SSH service on a non-default port reduces noise from automated scans and helps keep remote administration available when port 22 is filtered. Selecting an alternate port allows continued access through firewalls that block the default SSH port while still using the same authentication methods and keys.
The OpenSSH daemon sshd listens on the TCP port configured by the Port directive in /etc/ssh/sshd_config. After changing this directive and restarting sshd, the service begins accepting connections on the new port while leaving other settings such as host keys, ciphers, and user accounts unchanged.
Firewall rules and SELinux policies must allow traffic to the selected port or connection attempts will be dropped before reaching sshd. The chosen port must not be in use by another service, and configuration changes on systems without console access should be validated carefully to avoid lockouts after the daemon restarts.
$ ss -tlnp | grep 2222
$ sudo vi /etc/ssh/sshd_config
Any preferred text editor such as vi, nano, or vim can be used to modify /etc/ssh/sshd_config.
Port 2222
Leaving the original commented Port 22 line in place while adding another Port directive can cause confusion about which port is active and may leave sshd listening on an unintended port.
$ sudo sshd -t
No output from sshd -t indicates that the configuration syntax is valid.
$ sudo ufw allow 2222/tcp Rules updated Rules updated (v6)
On CentOS or Red Hat systems with firewalld, use sudo firewall-cmd --add-port=2222/tcp --permanent && sudo firewall-cmd --reload to open the port.
$ sudo semanage port -a -t ssh_port_t -p tcp 2222 ValueError: SELinux policy is not managed or store cannot be accessed.
Systems without SELinux enabled return an error like the above and do not require a port label update.
If semanage is unavailable on CentOS or Red Hat, install the tools with sudo yum install --assumeyes policycoreutils-python; if the port is already defined, replace -a with -m to modify the existing entry.
$ sudo systemctl restart ssh
$ sudo ufw delete allow 22/tcp
Deleting rules for port 22 before verifying connectivity on the new port can lock remote sessions out of the server if the new configuration is not reachable.
$ ss -tlnp | grep 2222
LISTEN 0 128 0.0.0.0:2222 0.0.0.0:* users:(("sshd",pid=16989,fd=3))
LISTEN 0 128 [::]:2222 [::]:* users:(("sshd",pid=16989,fd=4))
$ ssh -p 2222 user@host.example.net 'hostname' host