How to change SSH Port number!

I’m sure every one has noticed that when one receives a new VPS with an old IP, that when one logs into the VPS with SSH that there are virtually hundreds of login attempts no doubt bots that have been created by hackers.  Hackers know that the default port of SSH is 22.  So if one can change that number it may reduce the failed login attempts to almost zero.

Note that a certain amount of care has to be taken, as when one changes the SSH port it may affect other ports, the firewall and IP Table settings.  It may even have a further run on effect of conflicting with httpd and or nginx.

Here’s how one does it.

Step 1
Choose a random number between 49152 and 65535

Step 2
SSH into your VPS – if you don’t have VIM already loaded with CentoS – you can do it with this command:

yum install vim

Step 3
Use this command to edit the port number:

vim /etc/ssh/sshd_config

Scroll down to:

#Server 22

Delete # and replace 22 with your random number. Remember to make a note of the new number.

Vim tools:  to enter text use “i”, to get out “esc” and to save and exit “Shift  ZZ”

Step 4
Change IP tables (replace “newnumber” with your new port number):

iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport newnumber -j ACCEPT

iptables -A INPUT -j DROP -p tcp --dport 22

/etc/init.d/iptables save

Step 5
If you have a Panel, you also need to go into the Panel.  In VestaCP there is a separate setting for Firewall SSH port number – 22 – that has to be changed to the new number.

Step 6
Finally restart ssh service:

service sshd restart

Feedback: After the change of the port number I had no more bad login attempts. This really works well.