Change your server's SSH port using a startup script

Sometimes it's useful to be able to access your server using a different SSH port to the usual 22. There may be cases where your own outgoing port 22 is blocked due to a firewall that you cannot configure or due to other cases out of your control.

How to Change SSH Port

You can change  port while your server boots by providing a small script, usually known as a "startup script" or "init script" via systemctl. This special script runs when your server is built for the first time and is useful for quickly configuring and bootstrapping a server.  

SSH settings are usually stored in /etc/ssh/sshd_config but this may change depending on the distribution you pick when selecting a server. This guide assumes you are using Ubuntu.

One simple way to change the port that ssh is listening to is to simply insert a new line into its configuration file.

echo "Port <your chosen port number>" >> /etc/ssh/sshd_config
systemctl restart sshd

When creating a server, you can insert this bash script to change your SSH port. Pick a port that is open for you and isn't blocked by a firewall. Once the server has booted, you will be able to login to your server using the port you set.

To login to your server, you can use the -p argument for ssh to designate a port

ssh  -p <port> root@<your_server_ip>

You can then connect to your VPS via an SSH client like PuTTy, simply changing the "Port" field to the one you enabled.

You need a VPS for this SSH port tutorial? Sign up for BitLaunch.