How to append authorized_keys on the remote server with id_rsa.pub key from the local machine with a single command?
6 Answers
ssh-copy-id user@remote_server
-
4This should be he approved answer; the others may be useful if needing to troubleshoot but they are hack-y alternatives to the official recommended method. Jan 29, 2019 at 10:32
-
1This of course only works if one is authorized to login to host with user/pass alone. Otherwise one will need to find a way to append to authorized_keys manually from within a shell on host system. How one chooses to do this is an exercise for the reader. Oct 17, 2020 at 23:28
-
None of these answers work if you do not have access to log into the remote server.– DougOct 18, 2020 at 17:27
Adding an authorized key could be one-lined this way (use double-quotes so it's interpreted before sent):
ssh user@server "echo \"`cat ~/.ssh/id_rsa.pub`\" >> .ssh/authorized_keys"
-
Been using
ssh-copy-id
before but this command is great if you have a new public key (eg a new laptop) you want to add to one or a few servers that you already have access to. This allows you to authenticate using keys/settings from~/.ssh/
but copy a different key. Bravo! Feb 28, 2021 at 20:47
This does the trick:
cat ~/.ssh/id_rsa.pub | (ssh user@host "cat >> ~/.ssh/authorized_keys")
Appends the local public key the remote authorized_keys
file.
-
@user3132194 parentheses are used for grouping here ... making sure the >> is on the remote shell– wcochranApr 14, 2017 at 13:40
-
1
ssh user@host "cat >> ~/.ssh/authorized_keys" < ~/.ssh/id_rsa.pub
is a bit shorter and no subshell needed.– SameerJul 5, 2017 at 17:19 -
1I was trying to add Windows 10 built in openssh keys to my linux host, and this worked
type %userprofile%\.ssh\id_rsa.pub | ssh user@linux.local "cat >> .ssh/authorized_keys"
– AdarshaFeb 27, 2021 at 4:51
The ssh-copy-id
program is the standard way but the key can be appended manually to the ~/.ssh/authorized_keys
file:
cat ~/.ssh/id_rsa.pub | ssh username@host "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"
This does not check if the key already exists and can lead to duplicates.
The most convenient option is the ssh-copy-id
command. It can append the public key to ~/.ssh/authorized_keys
. For example:
ssh-copy-id -f -i id_rsa.pub username@host
Where:
-f
: force mode -- copy keys without trying to check if they are already installed-i
:[identity_file]
You can avoid some of the quoting with:
ssh user@host tee -a .ssh/authorized_keys < ~/.ssh/id_rsa.pub