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
}