Try this (newlines optional):
cat ~/.ssh/id_rsa.pub |
ssh <REMOTE> "cat > tmp.pubkey ;
mkdir -p .ssh ;
touch .ssh/authorized_keys ;
sed -i.bak -e '/$(awk '{print $NF}' ~/.ssh/id_rsa.pub)/d' .ssh/authorized_keys;
cat tmp.pubkey >>.ssh/authorized_keys;
rm tmp.pubkey"
Make sure to replace <REMOTE>
with the hostname you are trying to connect to. Also change id_rsa.pub
to whatever your pub key is called.
Cases covered by this:
- The remote host might not have an
.ssh
directory
authorized_keys
file might not exist
- If
authorized_keys
does exist it and you want to replace/update/add your ssh public key, this will work without duplicating the entry. This script replaces an entry if there is already one with the same comment.
ssh-copy-id
doesn't require the private part of the key. All it requires is the public part and the ability to log into the target host (which may require that you type your password or otherwise authenticate). What makes you think that the private key is required? This looks like an XY problem.ssh-copy-id
(as of OpenSSH 6.0) doesn't take care of not creating duplicate entries, so you could be unhappy about it for this reason.