Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
    }
share|improve this question

1 Answer 1

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;"
share|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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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