Server Administration

GCP: How to Recover Your SSH Login When You Forget Your Custom SSH Port?


GCP with VM instances.

Firstly, here is how to change the default SSH port

You can change the default SSH port from 22 to something else in sshd_config then restart your sshd service – make sure keep your current SSH connection open until your new port is verified to avoid locked out of your VM. We also need to added the new ssh port to ufw then remove the default 22 from your ufw allow list. For GCP, you need to update the SSH port for using IAP for TCP forwarding.

gcloud compute firewall-rules create allow-ssh-ingress-from-iap 
  --rules=tcp:your_new_ssh_port (ie: 2233) 

After changing the default SSH port, you need to access your SSH connection by Open in browser window on custom port.

What if you forget your custom SSH port?

Fortunately, there are two tools you can use: GCP Serial Console and Startup Script.

In the first step you need to create a new SSH user by using the startup script which looks like below:

useradd USERNAME
echo USERNAME:PASSWORD | chpasswd
usermod -aG google-sudoers USERNAME

Then reset your VM instance to allow it to create the new user. The next step is to edit your VM instance and check Enabling connection through serial ports under Remote Access.

Lastly, you can connect your instance via the Serial Console which will require you to use the login username and password you set earlier. Once logged in, you can see what custom port was specified in the /etc/ssh/sshd_config, and make sure you save it in your password manager!

By Ethan

To many, a business is a lifetime commitment. It's easy to start one yet difficult to make it successful. Attitude, skills, experiences and dedication help hone the craft along the way, but it's often the great vision and resilience to remain focused wins the game. Read more about me here