I have setup a droplet and logged in as root, I have added a new user and want to copy the ssh key from root to new user is there a command to copy ssh keys between 2 different users on the same server? on ubuntu I use “rsync --archive --chown=ubuntu:ubuntu ~/.ssh /home/ubuntu”
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Click below to sign up and get $100 of credit to try our products over 60 days!
Hi,
I usually use the generic commands to accomplish such tasks. They works well across different Linux distros.
So, you have ssh’d your droplet as root, and created your new user, let’s call it newuser.
Firstly, let’s find out what newuser’s home directory is.
It should be a subdirectory of
/home
directory, as above, with a name of your newly created user (newuser in our example), unless you changed your system environment or explicitely specified different home directory creating your newuser.Now, we are going to create
.ssh
directory to store your ssh public key. Note--parents
parameter ofmkdir
command. Thanks to itmkdir
creates full path specified with the command. If, for some reasons, your newuser’s home directory has not been created yet,mkdir --parents
will create it with its.ssh
subdirectory at once.Let’s copy ssh public key now. It is stored in
/root/.ssh/authorized_keys
file. This file may contain many different ssh public keys. In such case, you would have to extract the one you would be interested in. But, in our case, you have just one public key in this file, so you can straight copy a whole file.It almost done. Just one thing more. Note that we have done all the operations as a root, so both
.ssh
directory andauthorized_keys
file are owned by root. Our newuser must own them then. To do that accurately we need to find out what newuser’s initial login group ID is. At the beginning of this post we revealed what newuser’s home directory is. We can find out what newuser’s initial login group ID is from the same given output.The first number is a user ID, the second one is its initial login group ID. Having all the needed info, we are going to (re)assign an owner for newuser’s home directory and all its content, including subdirectories and their content (thanks to
--recursive
parameter).Job done :-) I hope it helps.
This comment has been deleted