Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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/ | 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/`.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
up vote 1 down vote accepted

Just use a variable, like this:

KEY=$(cat ~/.ssh/ 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


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.