If you need to update the public key you use for logging in to a server using ssh, you can do the following:
Just in case it’s a good idea to have a first shell open in parallel with a connection to the remote server:
Replace YOUR_SERVER_NAME by the hostname or IP address of the remote server. If you login with another user than root, replace root by the appropriate user name.
Then open a new shell and go to the subdirectory where your keys are stored:
First you should first backup the existing keys in case you run into problems:
cp id_dsa id_dsa.OLD cp id_dsa.pub id_dsa.pub.OLD
Then you can generate new keys. For this, you need to generate them using new files since you still need the old key in order to copy the new key to the server:
ssh-keygen -t dsa -f ~/.ssh/MY_NEW_KEY
Press Enter for each question asked.
This will create two files MY_NEW_KEY and MY_NEW_KEY.pub.
Now you need to copy the new public key to your server:
cat ~/.ssh/MY_NEW_KEY.pub | ssh root@YOUR_SERVER_NAME "cat >> ~/.ssh/authorized_keys"
Now you have both public keys in the authorized_keys file on the server and you need to delete the old key from the file:
ssh root@YOUR_SERVER_NAME vi ~/.ssh/authorized_keys
Then go to the line with the old key, press “dd” to delete the line and “ZZ” to save the file.
Then go back to your local shell:
Now you can replace your old public key by the new one and test whether it still works:
mv MY_NEW_KEY id_dsa mv MY_NEW_KEY.pub id_dsa.pub ssh root@YOUR_SERVER_NAME
If nothing works anymore and you want to roll it all back, you can do the following:
In the second shell:
Copy the output of “cat” and in the first shell:
Then delete the new key (with “dd”) and paste the old key back in there (press “i” before pasting to get in insert mode and escape after pasting to exit insert mode, and then “ZZ” to save).