How to Change Your SSH Port Safely on Any Linux Server (Ubuntu, Debian, CentOS, AlmaLinux)

Changing your SSH port is a simple yet powerful way to reduce brute-force login attempts and improve server security. To make this process easier, Hosteons offers a free Bash script that automatically handles the switch across all major Linux distributions — including firewalls and SELinux!


✅ Supported Operating Systems

  • Ubuntu 20.04 / 22.04
  • Debian 11 and above
  • CentOS 7 / 8
  • AlmaLinux 8 / 9

⚠️ Important Disclaimer

Changing your SSH port can lock you out if anything goes wrong.

Make sure you have console access such as VNC, IPMI, or KVM before using this script.


🔧 What the Script Does

  • Prompts until a valid SSH port is provided
  • Edits /etc/ssh/sshd_config to set the new port
  • Adds firewall rules for:
    • UFW (Ubuntu/Debian)
    • firewalld or iptables (CentOS/AlmaLinux)
  • Handles SELinux with semanage if needed
  • Restarts SSH service safely without reboot

🧰 How to Use the Script

  1. SSH into your VPS or server as root
  2. Run the following commands:
wget https://raw.githubusercontent.com/hosteons/SSH-Port-Changer-Script/main/ssh_port_changer.sh
chmod +x ssh_port_changer.sh
./ssh_port_changer.sh
  1. Enter your desired new SSH port when prompted

📦 Download from GitHub

Access the script and full documentation here:

👉 https://github.com/hosteons/SSH-Port-Changer-Script

How to update SSH Port in CentOS 7

Update SSH Port in CentOS 7

Here are few simple steps on how to update SSH Port in CentOS 7 VPS or Dedicated Server

Edit the SSHD configuration file :

nano -w /etc/ssh/sshd_config

(if nano is not installed use any other text editor or install it with yum -y install nano)

and change the Port number from 22 to any custom port you choose :

e.g. Port 18989

Make sure to even remove the # mark before Port

Save the config file

SELinux is enabled by default in CentOS 7 so you need to even inform SELinux to change the SSH Port else it won’t allow you to restart SSHD with new Port.

To run semanage for updating SSHD Port you nee to first install policycoreutils, install it with :

yum -y install policycoreutils-python

now update SeLinux policy to allow new port for SSH service. to do this, run below :

semanage port -a -t ssh_port_t -p tcp 18989

now you need to update Firewall policy to allow new SSH Port, to do this run below :

firewall-cmd –permanent –zone=public –add-port=18989/tcp
firewall-cmd –reload
systemctl restart sshd.service

SSHD Port is now updated, you can now connect to your new SSH Port: 18989