There are plenty of tutorials out there for a straightforward SSH key copy, but none that would check if the key doesn't already exists remotely. This should work:

cat ~/.ssh/id_rsa.pub | ssh -p <port> <user>@<hostname> 'sh -c "if ( ! grep -q '`cat -`' ~/.ssh/authorized_keys); then cat - >>~/.ssh/authorized_keys; fi"'

The cat - inside the grep doesn't get interpolated into a single string but 3, and that throws the whole thing off. I did it in Ruby and it works, but it's not ideal. Any bash pro around?

  Net::SSH.start(<host>, <username>, :password => <password>, :port => <port>) do |ssh|
    local_public_key = `cat ~/.ssh/id_rsa.pub`.chomp
    ssh.exec! %{
      if ( ! grep -q '#{local_public_key}' ~/.ssh/authorized_keys ); then echo '#{local_public_key}' >> ~/.ssh/authorized_keys; fi
    }
link|improve this question

75% accept rate
feedback

1 Answer

up vote 1 down vote accepted

Just use a variable, like this:

KEY=$(cat ~/.ssh/id_rsa.pub) ssh -p <port> <user>@<hostname> "if [ -z \"\$(grep \"$KEY\" ~/.ssh/authorized_keys )\" ]; then echo $KEY >> ~/.ssh/authorized_keys; echo key added.; fi;"
link|improve this answer
Excellent! Now I just need to figure the command-line expect to pass the password and I'm done. – gerhard Mar 27 '11 at 15:16
feedback

Your Answer

 
or
required, but never shown

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