Created
May 10, 2015 16:09
-
-
Save mitio/1383a67ed47706d6f83a to your computer and use it in GitHub Desktop.
Quick and dirty script to replace SSH heys on multiple hosts you manage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Omit the email part from the SSH public key as it may vary | |
old_key='ssh-rsa AAAAB3Nz...PpZ97Q==' | |
# The full SSH public key here, including the email ID part | |
new_key='ssh-rsa AAAAB3Nz...TfcYCcQ== [email protected]' | |
# Set to 1 to make the script spit out SSH connection errors | |
verbose=0 | |
# List of users & hosts to check & replace SSH keys on | |
hosts=" | |
[email protected] | |
[email protected] | |
[email protected] -p 2222 | |
" | |
if [ "$1" == "replace" ]; then | |
echo '** Working in REPLACE MODE **' | |
replace="yes" | |
else | |
echo '** Working in check-only mode. Pass "replace" as an argument to perform actual replacement. **' | |
replace="" | |
fi | |
ssh_options="-o PasswordAuthentication=no" | |
today=`date +'%Y-%m-%d'` | |
OLD_IFS=$IFS | |
IFS=" | |
" | |
for host in $hosts; do | |
IFS=$OLD_IFS | |
echo -n "$host - " | |
if [ $verbose == 1 ]; then | |
ssh $ssh_options $host "grep '$old_key' ~/.ssh/authorized_keys >/dev/null </dev/null" | |
else | |
ssh $ssh_options $host "grep '$old_key' ~/.ssh/authorized_keys >/dev/null </dev/null" >/dev/null 2>&1 | |
fi | |
if [ $? == 0 ]; then | |
if [ "$replace" == "yes" ]; then | |
temp_keys_file="/tmp/authorized_keys.temp" | |
if ssh $ssh_options $host " | |
echo '$new_key' >> ~/.ssh/authorized_keys && | |
grep -v '$old_key' ~/.ssh/authorized_keys > $temp_keys_file && | |
mv ~/.ssh/authorized_keys ~/.ssh/authorized_keys-$today && | |
mv $temp_keys_file ~/.ssh/authorized_keys && | |
rm -f $temp_keys_file | |
"; then | |
echo "found & replaced" | |
else | |
echo "**FOUND BUT FAILED TO REPLACE**" | |
fi | |
else | |
echo "found" | |
fi | |
else | |
if ssh $ssh_options $host 'date' >/dev/null 2>/dev/null; then | |
echo "**MISSING**" | |
else | |
echo "**UNABLE TO CONNECT**" | |
fi | |
fi | |
IFS=" | |
" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment