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? */
link|improve this question

64% accept rate
feedback

1 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.

link|improve this answer
"You cannot" -> I can, it is like trying to run "ssh-copy-id" every time before connecting or auto-executing certain commands after connecting. – Vi. Mar 30 '11 at 10:34
Fine, you can run ssh-copy-id every time before connecting - but IMHO, that's lazy and ineffective. (In my $LOCATION, a SSH handshake may take up to 5 seconds on occassions, that's why I don't like it.) Copying the key once would be enough - just remember to do it the first time you connect to a new server. (If you manage tens or hundreds of servers, then you're using the wrong authentication method.) – grawity Mar 30 '11 at 10:38
"just remember to do it the first time you connect to a new server" -> such things should be "remembered" by computer, not user. – Vi. Mar 30 '11 at 14:59
@Vi: But only the user knows whether the key should be copied to the remote system (and if yes, which key: I have four). Also, where exactly the key should be put and in which format - OpenSSH has one, but not the only (unfortunately, RFC 4819 is not very common). – grawity Mar 30 '11 at 18:40
@Vi: This hack may work as a ProxyCommand in your SSH client config. – grawity Mar 30 '11 at 18:44
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.