To my surprise, I discovered that ssh-copy-id fails if you do not have the private part of the key, making it not usable for deploying someone else key.

I an looking for a reliable way to deploy these keys, so it must not create duplicate entries if you run it twice.

  • No, ssh-copy-id doesn't require the private part of the key. All it requires is the public part and the ability to log into the target host (which may require that you type your password or otherwise authenticate). What makes you think that the private key is required? This looks like an XY problem. Jan 31, 2015 at 22:26
  • However, ssh-copy-id (as of OpenSSH 6.0) doesn't take care of not creating duplicate entries, so you could be unhappy about it for this reason. Jan 31, 2015 at 22:27
  • ssh-copy-id is a bash script, so you can adopt it for your needs. @Gilles ssh-copy-id filters out duplicate entries with attempting to log in with the new keys. Feb 20, 2019 at 9:09
  • If private part of the key is not required, then here is another solution: unix.stackexchange.com/questions/564707/… Mar 1 at 18:42

1 Answer 1


Try this (newlines optional):

cat ~/.ssh/id_rsa.pub |
ssh <REMOTE> "cat > tmp.pubkey ;
              mkdir -p .ssh ;
              touch .ssh/authorized_keys ;
              sed -i.bak -e '/$(awk '{print $NF}' ~/.ssh/id_rsa.pub)/d' .ssh/authorized_keys;
              cat tmp.pubkey >>.ssh/authorized_keys;
              rm tmp.pubkey"

Make sure to replace <REMOTE> with the hostname you are trying to connect to. Also change id_rsa.pub to whatever your pub key is called.

Cases covered by this:

  1. The remote host might not have an .ssh directory
  2. authorized_keys file might not exist
  3. If authorized_keys does exist it and you want to replace/update/add your ssh public key, this will work without duplicating the entry. This script replaces an entry if there is already one with the same comment.
  • I would advice to add a umask to create proper file permission. So ssh <REMOTE> "umask 0077; cat > tmp.pubkey ; (...)
    – Huygens
    Mar 1, 2015 at 15:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .