Skip to content

Instantly share code, notes, and snippets.

@sakatam
Last active December 31, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakatam/7905406 to your computer and use it in GitHub Desktop.
Save sakatam/7905406 to your computer and use it in GitHub Desktop.
Here's how to add a public key to multiple servers in one shot. The script below avoids duplicated entry by grepping the authorized_keys file in advance.

Template script:

$ PUB="paste your pubkey here"
$ for h in %LIST OF HOSTS%; do echo -n "$h -> " && ssh ec2-user@${h} "if grep -Fxq \"${PUB}\" .ssh/authorized_keys; then echo 'the pubkey already exists'; else echo \"${PUB}\" >> .ssh/authorized_keys && echo \"the pubkey was added\"; fi"; done

Example usage:

$ PUB='ssh-rsa XXXXXXXXXXXXXXXXXXXXX== foo'
$ for h in dev1 dev2 dev3; do echo -n "$h -> " && ssh ec2-user@${h}.mydomain.com "if grep -Fxq \"${PUB}\" .ssh/authorized_keys; then echo 'the pubkey already exists'; else echo \"${PUB}\" >> .ssh/authorized_keys && echo \"the pubkey was added\"; fi"; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment