How to change the default SSH port on Linux
Login via SSH
First of all, login to your server via SSH as user root
Note that if SSH is listening on the default port 22, there is no need to specify the port. When the port will be changed, you will need to specify if when logging to the server via SSH. For example, if SSH is listening on port 1012 we can login to the server using the following command:
ssh root@IP_Address -p1012
Updated Installed Packages
Once you are logged in to the VPS as user root update the installed packages.
CentOS / Fedora
yum update -y
Ubuntu / Debian
apt-get update $$ apt-get upgrade
Open the SSH Configuration File
Once the system is updated, open the SSH configuration file with your favorite text editor and find the lines that specifies the SSH port.
vim /etc/ssh/sshd_config #Port 22
Change SSH Port Number
Uncomment the relevant line by removing the # sign and change the default port 22 to the one that you want to use. In this article we will use port 1012.
Save the changes and exit.
NOTE: Before changing the port, you should make sure that the new port is free and it is not used by another service on your VPS. You should also check if the port is not closed in your server firewall.
Restart SSH Service
Now, restart the SSH service for the changes to take effect.
service sshd restart
6. Check SSH Port
Once restarted, SSH will listen on port 1012. You can check this by executing the following command in the terminal
netstat -tunlp |grep ssh tcp 0 0 0.0.0.0:1012 0.0.0.0:* LISTEN 497/sshd
According to the output of the netstat command, the SSH port is changed, and it is now listening on port 1012.