Changing the SSH Port

Sometimes you don’t want SSH running on standard port 22. Here are the steps to change it:

It’s VERY important that you leave port 22 open while you are testing the new port, otherwise you may lock yourself out of the server!
SSH into the server normally…

cp /etc/ssh/sshd_config /etc/ssh/sshd_config.root

In the /etc/ssh/sshd_config.root file that you just made, specify a new port number with the Port line:

Port 9670
#Protocol 2,1
#ListenAddress 0.0.0.0
#ListenAddress ::

Also, make sure that PermitRootLogin is set to yes or commented out.
Now open /etc/init.d/sshd and locate this section:

# Some functions to make the below more readable
KEYGEN=/usr/bin/ssh-keygen

Directly below that, add this line:

OPTIONS=”-f /etc/ssh/sshd_config.root”

Now locate this line:

initlog -c “$SSHD $OPTIONS” && success || failure

Directly ABOVE that add this line:

initlog -c “$SSHD” && success || failure

Now you need to restart sshd (service sshd restart). Before shutting down port 22, make sure that whatever port you created for ssh is either opened in the firewall or has the appropriate IPs added. Make sure to test this in a separate ssh window to make sure you can log in!

Once you’ve verified that you can log in through the new port, you have a couple options for port 22.

  • Close it altogether or just open it for specific IPs as usual
  • Disable root logins through port 22 (preferred)

To disable root logins, open the original /etc/ssh/sshd_config file and uncomment out PermitRootLogin and set to No. This will essentially allow someone to log in as the user, but not root. You didn’t really change the SSH port, you’re just running a copy of it on another port and making port 22 useless.

If you want to disable port 22 altogether, you can just directly edit the /etc/ssh/sshd_config file and restart SSHD, but you only have one chance to get it right.

Once the port is changed you would ssh into the server with the command ssh -p 9670 root@server with 9670 being the port you chose for ssh.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *