How to change the SSH port in Linux


How to change the SSH port in Linux

You are here:

The SSH port listens on port 22 by default. It’s strongly recommended to change the default SSH port from the standard 22 to a more obscure number to further protect your server against brute-force attacks by bots and malicious users.

In this guide we’ll provide the required steps for changing the SSH port on a Linux server as well as making appropriate firewall changes to allow access to the newly designated port.

Note: this requires root access and should take no longer than a couple of minutes once logged in to your server.

Linux reserves ports 1 to 1024 for well known services and it is recommended to pick a number outside of this range.

We’ll use Port 9922 as an example here. Feel free to use a totally different number but just change the numbers in the commands provided to match.

Changing the port in SSH config

First we need to edit the sshd_config file in /etc/ssh/ – using your chosen text editor, go ahead and open up the file ready for editing. We’ll be using nano.

nano /etc/ssh/sshd_config

You should see a line with #Port 22. We want to edit this line to change 22 to 9922 and remove the # from the start of the line:

Port 9922

Save and exit the file.

Now restart the SSHD service, with one of the following commands – depending on OS version (it’s okay to try both!)

service sshd restart
systemctl restart sshd

(Optional) You can double check the SSH port change has worked by running one of the commands below, where you should see an entry containing 9922 and ssh or sshd.

ss -tulpn | grep ssh
netstat -tulpn | grep ssh

Allowing the new port in the firewall

This part of the guide requires you to know which firewall you are using on your server. Be careful here as incorrect syntax or changes can lock you out of your server.

If you are using FirewallD (default in CentOS) then you can use the following commands to open the new port.

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

If you are also using SELinux you will need to adjust the SELinux rule to allow the new port.

semanage port -a -t ssh_port_t -p tcp 9922

If you are using iptables, you can use the following command to open the new port.

iptables -A INPUT -p tcp --dport 9922 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

If you are using UFW then you can simply run the following commands:

ufw allow 9922
ufw enable

You should now be able to SSH into your server using the new SSH port. To secure your SSH service even further we would recommend setting up SSH key-based authentication and disable password authorization.

Table of Contents