How to append authorized_keys on the remote server with id_rsa.pub key

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

Upvotes: 62

Views: 122360

Answers (7)

NiKiZe
NiKiZe

Reputation: 1450

As mentioned ssh-copy-id should be the preferred way.

In some cases you want more than one key, for example to append all local authorized_keys to the remote, and not creating duplicates:

cat ~/.ssh/authorized_keys | ssh user@remote "while read p; do grep -q \"$p\" ~/.ssh/authorized_keys || echo \"$p\"; done >> ~/.ssh/authorized_keys"

Local cat ~/.ssh/authorized_keys can be replaced by cat ~/.ssh/id_rsa.pub instead.

Permissions/owner on .ssh and .ssh/authorized_keys should be 700/600 respectively, and might need to be fixed separately if not correct from the beginning.

Upvotes: 0

user260532
user260532

Reputation: 51

You can avoid some of the quoting with:

ssh user@host tee -a .ssh/authorized_keys < ~/.ssh/id_rsa.pub

Upvotes: 5

Miroslaw
Miroslaw

Reputation: 231

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]

Upvotes: 13

Mose
Mose

Reputation: 886

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"

Upvotes: 63

user4804619
user4804619

Reputation:

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.

Upvotes: 14

Doug
Doug

Reputation: 3883

ssh-copy-id user@remote_server

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

Upvotes: 122

wcochran
wcochran

Reputation: 10896

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.

Upvotes: 32

Related Questions