Skip to content

Instantly share code, notes, and snippets.

@daevski
Created February 5, 2021 05:37
Show Gist options
  • Save daevski/4d0b3964dc3051ba3ba06b5059afb43e to your computer and use it in GitHub Desktop.
Save daevski/4d0b3964dc3051ba3ba06b5059afb43e to your computer and use it in GitHub Desktop.
Copy a public key to multiple servers, authenticating with an existing private key.
#!/bin/bash
# Use this script to replace a public key on multiple servers.
# Note that the path to the authorized_keys file is not a varible at the moment, so if you change 'me' variable, you may also want to change that path to "/home/${me}/.ssh/authorized_keys". I would but I don't want to escape anymore quotes tonight...
me=dmckee
key_path=$HOME/.ssh/current_private_key
pub_path=$HOME/.ssh/new.pub
declare -a hosts=(
"myserver1.domain.com"
"myserver2.domain.com"
"myserver3.domain.com"
)
# CHANGE THE VARIABLES ABOVE !!
# This is a command used on the remote system to remove duplicate lines in the authorized_keys file, since the `-f` option may create duplicates.
unique_authfile='a=$HOME/.ssh/authorized_keys;awk '"'"'!x[$0]++'"'"' "${a}" > "${a}"2;cat "${a}"2 > "${a}";rm "${a}"2'
for host in "${hosts[@]}"; do
echo "Pushing to system: ${host} ..."
ssh-copy-id -f -i "${pub_path}" -o "IdentityFile ${key_path}" "${me}@${host}"
echo "Cleaning up authorized_keys file ..."
ssh -i "${pub_path/.pub/}" "${me}@${host}" "eval $unique_authfile"
done
# MANUAL TEST AFTERWARDS
# ssh -o "IdentityFile ${pub_path/.pub/}" "${me}@${hosts[0]}" 'cat $HOME/.ssh/authorized_keys'
# ssh -o "IdentityFile ${pub_path/.pub/}" "${me}@${hosts[1]}" 'cat $HOME/.ssh/authorized_keys'
# ssh -o "IdentityFile ${pub_path/.pub/}" "${me}@${hosts[2]}" 'cat $HOME/.ssh/authorized_keys'
# ssh -o "IdentityFile ${pub_path/.pub/}" "${me}@${hosts[3]}" 'cat $HOME/.ssh/authorized_keys'
# etc...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment