Skip to content

Instantly share code, notes, and snippets.

@hrickards
Forked from jsachs/cycle-pem.sh
Last active March 8, 2017 20:22
Show Gist options
  • Save hrickards/bb756ee4698bbacb53c4ccb5cf73b57e to your computer and use it in GitHub Desktop.
Save hrickards/bb756ee4698bbacb53c4ccb5cf73b57e to your computer and use it in GitHub Desktop.
shell script to replace authorized_keys in an EC2 instance
#!/bin/bash
# this script should be used in a dir with both the old
# private key and the new public key
oldpem=$1
user=$2
newpub=$3
newpem=$4
# fill in any hosts you want to use
# each host should require the same user, like 'ubuntu' or 'centos'
HOSTS="localhost"
[ $# -ne 4 ] && { echo "Usage: $0 <old_privkey.pem> <user> <new_pubkey> <new_privkey.pem>"; exit 1; }
for HOSTNAME in ${HOSTS} ; do
scp -i $oldpem $newpub $user@$HOSTNAME:$newpub
ssh -i $oldpem $user@$HOSTNAME "cat $newpub >> .ssh/authorized_keys"
ssh -i $newpem $user@$HOSTNAME "cat $newpub > .ssh/authorized_keys"
ssh -i $newpem $user@$HOSTNAME "if [ -x \"$(command -v restorecon)\" ]; then restorecon -Rv .ssh/authorized_keys; fi"
done
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment