How do you copy the public key to a ssh-server?

OpenSSH comes with a command to do this, ssh-copy-id. You just give it the remote address and it adds your public key to the authorized_keys file on the remote machine:

$ ssh-copy-id [email protected]

You may need to use the -i flag to locate your public key on your local machine:

$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

You could always do something like this:

scp ~/.ssh/id_rsa.pub [email protected]:/tmp/id_rsa.pub
ssh [email protected] 
cat /tmp/id_rsa.pub >> ~/.ssh/authorized_keys

I am not sure if you can cat from a local machine into an ssh session. Just move it to /tmp as suggested.

Edit: This is exactly what ssh-copy-id does. Just like Michael said.


This answer describes how to make the intended way shown in the question working.

You can execute a shell on the remote computer to interpret the special meaning of the >> redirection operator:

ssh [email protected] sh -c "'cat >> .ssh/authorized_keys'" < /home/tim/.ssh/id_rsa.pub

The redirection operator >> is normally interpreted by a shell.

When you execute ssh host 'command >> file' then it is not guaranteed that command >> file will be interpreted by a shell. In your case command >> file is executed instead of the shell without special interpretation and >> was given to the command as an argument -- the same way as running command '>>' file in a shell.

Some versions of SSH (OpenSSH_5.9) will automatically invoke shell on the remote server and pass the command(s) to it when they detect tokens to be interpreted by a shell like ; > >> etc.

Tags:

Ssh