How to replace an SSH key on your VPS¶
This page will show you how to replace an SSH key on your VPS, in the event you lost the SSH key associated with the server.
The first step is to generate a new SSH public and private keypair on your local machine
Next, activate rescue mode for the VPS
Once rescue mode is activated, connect to the Emergency Console
While connected to the console, login to the Rescue Mode OS with the username ‘root’ and no password
Mount the system disk of your VPS, which under Rescue Mode, for a server with a single disk, will be /dev/xvdb1:
$ mkdir disk $ mount /dev/xvdb1 disk/
The system disk will always be the first partition of the last disk in /dev/, sorted alphabetically.
As the console does not support copy/paste, and entering a public-key by hand is error-prone, one option to get the new SSH public key onto the server would be to use a pastebin service.
Upload your new SSH public key to the pastebin service
Locate the URL of the raw data (e.g. https://pastebin.com/raw/UNIQUECODE)
Use cURL to download the raw data and append it to your authorized_keys file for the user
$ curl https://pastebin.com/raw/UNIQUECODE >> disk/home/debian/.ssh/authorized_keys
Then, using your favorite text editor, view the contents of the file and ensure there are no line-breaks or spaces
You can optionally remove the previous lines in the authorized_keys file to revoke SSH access for your older SSH keypair(s)
Save and close the file
Check the permissions on the file, and ensure the file is owned by uid 1000 and gid 1000 :
$ ls -n disk/home/debian/.ssh/authorized_keys -rw------- 1 1000 1000 806 Dec 9 17:00 disk/home/debian/.ssh/authorized_keys
As a final confirmation, unmount the disk, mount it again, check the content of the file, and then unmount the disk
$ umount disk $ mount /dev/xvdb1 disk/ $ cat disk/home/debian/.ssh/authorized_keys $ umount disk
Congrats! Once you server has rebooted following the deactivation of the rescue mode, you should be able to SSH into your VPS using the new SSH key.