Question
How to change the SSH port number on a Linux server?
Answer
-
Connect to the server via SSH.
-
Open the SSH configuration file
/etc/ssh/sshd_config
in any text editor. In this example we are using the vi editor:# vi /etc/ssh/sshd_config
-
Modify the file according to your needs using one of these steps:
Warning: Be careful when modifying the file. The incorrect SSH configuration may lead to server inaccessibility via SSH.
-
Set up one custom SSH port
Remove the hash "#" in the line
#Port 22
and specify your custom SSH port, which will be used instead of standard SSH port 22.
Example:Port 2222
-
Set up several SSH ports
Remove the hash "#" in the line
#Port 22
and additionally add your custom SSH port on the next line. In this case, SSH connections will be available on both ports.
Example:Port 22
Port 2222
-
-
Save the changes and close the file.
-
Restart the sshd service to apply the changes:
# service sshd restart
Note: The new port must be opened in server firewall. Visit this KB article to find out how.
Note: If port is changed on a SELinux system, it is needed to tell SELinux about this change:
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
If the Fail2Ban ssh jail is enabled on the server, modify its configuration to meet new changes:
-
Go to Tools & Settings > IP Address Banning (Fail2Ban) > switch to the Jails tab and click ssh.
-
On the ssh page, click Change Settings and change the port value from ssh to your new custom SSH port (In this example, it is 2222). Once done, apply the changes.
Note: If the default port (22) and custom port are used, add them as "port=2222".