I needed that to add jenkins pubkey to my host's
authorized_keys when starting a docker container with jenkins. Looked for solutions, but could not find ready at internet. May seem obvious, but not for me at least :)
PUBKEY=$(cat ~/.ssh/id_rsa.pub); grep -q "$PUBKEY" ~/.ssh/authorized_keys || echo "$PUBKEY" >> ~/.ssh/authorized_keys
This one-liner checks whether pubkey is already present in
authorized_keys file, and appends it to the end of file if it is not present.
~/.ssh/id_rsa.pub here is path to pubkey being added
~/.ssh/authorized_keys here is a path to target
authorized_keys file (
~ symbol stands for ```
For remote host, one can use
You may want to skip the whole idea of messing around with ~/.ssh/authorized_keys and just use SSH CA feature as described, for example, here: https://www.digitalocean.com/community/tutorials/how-to-create-an-ssh-ca-to-validate-hosts-and-clients-with-ubuntu (scroll down to "How To Configure User Keys").
The beauty of this is that you configure your container once (by adding
TrustedUserCAKeys /etc/ssh/users_ca.pub where
users_ca.pub contains the public part of the CA key generated on your local machine) and from that point on if you want to grant access to the container to any key you just sign the public part of that key with your CA private key and specify which accounts are allowed for the key you are signing. Works like magic :)