57

How to append authorized_keys on the remote server with id_rsa.pub key from the local machine with a single command?

shilovk
  • 11,718
  • 17
  • 75
  • 74

6 Answers6

113

ssh-copy-id user@remote_server

http://linux.die.net/man/1/ssh-copy-id

Doug
  • 3,472
  • 3
  • 21
  • 18
  • 4
    This 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. – olisteadman Jan 29 '19 at 10:32
  • 1
    This 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. – drkstr101 Oct 17 '20 at 23:28
  • 1
    None of these answers work if you do not have access to log into the remote server. – Doug Oct 18 '20 at 17:27
62

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"
boatcoder
  • 17,525
  • 18
  • 114
  • 178
Mose
  • 876
  • 7
  • 7
  • 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! – berezovskyi Feb 28 '21 at 20:47
32

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.

wcochran
  • 10,089
  • 6
  • 61
  • 69
  • @user3132194 parentheses are used for grouping here ... making sure the >> is on the remote shell – wcochran Apr 14 '17 at 13:40
  • 1
    `ssh user@host "cat >> ~/.ssh/authorized_keys" < ~/.ssh/id_rsa.pub` is a bit shorter and no subshell needed. – Sameer Jul 05 '17 at 17:19
  • 1
    I 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"` – Adarsha Feb 27 '21 at 04:51
14

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.

Kevin
  • 6,665
  • 1
  • 17
  • 14
12

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]
anothernode
  • 5,100
  • 13
  • 43
  • 62
Miroslaw
  • 221
  • 2
  • 8
5

You can avoid some of the quoting with:

ssh user@host tee -a .ssh/authorized_keys < ~/.ssh/id_rsa.pub
user260532
  • 51
  • 2
  • 2