Many times my colleagues have asked me how to change SSH port on CentOS 7. Obviously, the most straightforward solution (edit /etc/ssh/sshd_config) did not work: OpenSSH failed to restart, something like this:

Jul 29 03:54:24 localhost.localdomain systemd[1]: Starting OpenSSH server daemon...
-- Subject: Unit sshd.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit sshd.service has begun starting up.
Jul 29 03:54:24 localhost.localdomain sshd[23133]: error: Bind to port 522 on 0.0.0.0 failed: Permission denied.
Jul 29 03:54:24 localhost.localdomain sshd[23133]: error: Bind to port 522 on :: failed: Permission denied.
Jul 29 03:54:24 localhost.localdomain sshd[23133]: fatal: Cannot bind any address.
Jul 29 03:54:24 localhost.localdomain systemd[1]: sshd.service: main process exited, code=exited, status=255/n/a
Jul 29 03:54:24 localhost.localdomain systemd[1]: Failed to start OpenSSH server daemon.

The reason for “Permission denied” error is that the system has SELinux active, and by default, SELinux only allows port 22 for SSH.

Let us assume that we want SSH to run on port 522, and /etc/ssh/sshd_config has already been modified accordingly.

The first step is to install policycoreutils-python package if it is not installed:

sudo yum install -y policycoreutils-python

Then, we need to tell SELinux that the SSH daemon is going to use a different port (in our case, this will be 522):

sudo semanage port -a -t ssh_port_t -p tcp 522

Next, we need to enable access to that port in the firewall (CentOS 7 uses firewalld):

sudo firewall-cmd --permanent --zone=public --add-port=522/tcp
sudo firewall-cmd --reload

Finally, restart sshd:

sudo systemctl restart sshd.service

Congratulations, SSH daemon is now running on a different port.

CentOS 7: How to Change SSH Port
Tagged on:         

Leave a Reply

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