#!/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...