If I have a host I want to be able to connect to and I currently have a keyboard and monitor plugged in, how would I copy a key to a user so I can connect as that user remotely. Essentially I want to do the same thing as ssh-copy-id but without having to be able to connect over ssh first.
3 Answers
The keys are stored in a text file under $HOME/.ssh/authorized_keys.
To add a new key just copy the contents of the *.pub file of your key to a new line in this file.
Some more information is available on the SSH web site.
-
5When doing this manually, also make sure the file and directory permissions are set correctly. The
authorized_keysfile should be owned by either the user that is being authorized, or by root, and not be writeable by anyone else. The same applies to the~/.sshdirectory and the user's home directory. Otherwisesshdwill ignore theauthorized_keysfile as there is a possibility that another user may have had write access to it.telcoM– telcoM2019-02-23 08:19:05 +00:00Commented Feb 23, 2019 at 8:19
For example, use the commands below:
scp name_of_public_key.pub root@<remote IP address>:</home/user_home_folder or /root>
Then ssh log to remote host and go to home folder of user
cd
or
cd /home/name_of_user
then type:
cat name_of_public_key.pub >> .ssh/authorized_keys
Public key is added to end of file authorized_keys. Public key is not secret.
-
1The question says, "without having to be able to connect over ssh first," but
scpuses SSH to connect.Toby Speight– Toby Speight2022-10-25 05:44:19 +00:00Commented Oct 25, 2022 at 5:44
This oneliner will automate the process:
cat .ssh/id_ecdsa.pub | xargs -i ssh NameOfServer "echo {} >> .ssh/authorized_keys"
This script cats your public key, pipes it to exargs using the -i flag that will pass the piped in output to any {}. You then ssh into your target server and echo your pubkey into the authorized key file, giving you sshkey access.
However, it will fail if the target machine doesn't have a .ssh folder or authorized_keys file., so the following script solves that with a bash conditional:
cat .ssh/id_ecdsa.pub | xargs -i ssh $1 "if [[ ! -e .ssh/authorized_keys ]];
then mkdir .ssh; touch .ssh/authorized_keys; fi; echo {} >> .ssh/authorized_keys"
The if statement checks to if the target directory exists, and exits, or creates it first and then exits.
-
1This doesn't answer the question, which says, "without having to be able to connect over ssh first."Toby Speight– Toby Speight2022-10-25 05:43:37 +00:00Commented Oct 25, 2022 at 5:43
-
I read it as 'not using ssh-copy-id', since that was the title. Also, fundamentally, we're just adding an entry into the authorized_keys file, so cat'ing your public key and echoing it into .ssh/authorized_keys is generalizable to 'paste your pubkey into authorized_keys'Hydra– Hydra2022-11-08 21:09:11 +00:00Commented Nov 8, 2022 at 21:09