5

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 3

5

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.

1
  • 5
    When doing this manually, also make sure the file and directory permissions are set correctly. The authorized_keys file 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 ~/.ssh directory and the user's home directory. Otherwise sshd will ignore the authorized_keys file as there is a possibility that another user may have had write access to it. Commented Feb 23, 2019 at 8:19
1

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.

1
  • 1
    The question says, "without having to be able to connect over ssh first," but scp uses SSH to connect. Commented Oct 25, 2022 at 5:44
1

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.

2
  • 1
    This doesn't answer the question, which says, "without having to be able to connect over ssh first." Commented 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' Commented Nov 8, 2022 at 21:09

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.