Ssh-copy-id and duplicates in authorized_keys

authorized-keyspublic-keyssh

I want to type password only once when connecting to SSH so I use ssh-copy-id and install my pubkey into authorized keys.

But I don't keep track which servers already have my key and which does not, so I issue ssh-copy-id again sometimes which adds duplicate key to authorized_keys?

  1. How to prevent ssh-copy-id from installing the key when it is already installed?
  2. /* How to make key installation automatic and transparent when connecting to SSH (without explicit ssh-copy-id? */

Best Answer

How to prevent ssh-copy-id from installing the key when it is already installed?

Write your own script. All ssh-copy-id does is append a line to a file. The following would check for key's existence:

#!/bin/bash
cat ~/.ssh/id_* | ssh "$@" 'mkdir -pm 0700 ~/.ssh &&
    while read -r ktype key comment; do
        if ! (grep -Fw "$ktype $key" ~/.ssh/authorized_keys | grep -qsvF "^#"); then
            echo "$ktype $key $comment" >> ~/.ssh/authorized_keys
        fi
    done'

How to make key installation automatic and transparent when connecting to SSH (without explicit ssh-copy-id?

You cannot, because if the server doesn't have your public key already, it will not know where to get it from, either.

Related Question