Skip to content

Instantly share code, notes, and snippets.

@edoshor
Created March 21, 2020 17:28
Show Gist options
  • Save edoshor/e34bdffa773ef88658f92299bb0a99fb to your computer and use it in GitHub Desktop.
Save edoshor/e34bdffa773ef88658f92299bb0a99fb to your computer and use it in GitHub Desktop.
A small utility to automate replacement of ssh key on servers
#!/usr/bin/env bash
###################
# A small utility to automate replacement of ssh key on servers.
#
# USE WITH GREAT CARE !!!
# Author: [email protected]
set -e
set +x
copy_new() {
echo ssh-copy-id -i "$new_key" "${user:+"$user@"}$host" "${port:+"-p $port"}"
echo ssh -T -i "$new_key" "${user:+"$user@"}$host" "${port:+"-p $port"}" -o PasswordAuthentication=no
}
remove_old() {
ssh_cmd="ssh -o PasswordAuthentication=no -i $new_key ${port:+"-p $port"} ${user:+"$user@"}$host"
old_key_pub=$(cat "$old_key.pub")
new_key_pub=$(cat "$new_key.pub")
echo "$ssh_cmd" "\"sed -i 's#$old_key_pub##' ~/.ssh/authorized_keys\""
echo "$ssh_cmd" "\"grep -l \"$old_key_pub\" /home/**/.ssh/authorized_keys | xargs -L 1 sed -i 's#$old_key_pub#$new_key_pub#'\""
}
usage() {
echo "$0 [-h | --host] [-u | --user] [-p | --port] [-i | --new_key] [-k | --old_key]"
}
##### Main
host=
port=
user=
old_key="$HOME/.ssh/id_rsa"
new_key="$HOME/.ssh/id_rsa_new"
while [ "$1" != "" ]; do
case $1 in
-h | --host)
shift
host=$1
;;
-u | --user)
shift
user=$1
;;
-p | --port)
shift
port=$1
;;
-i | --new_key)
shift
new_key=$1
;;
-k | --old_key)
shift
old_key=$1
;;
--help)
usage
exit
;;
*)
usage
exit 1
;;
esac
shift
done
if [ -z "$host" ]; then
echo "No host was given"
usage
exit 1
fi
echo "$old_key => $new_key on ${user:+"$user@"}$host${port:+":$port"}"
echo "Copying new file"
copy_new
echo "Removing old file"
remove_old
@edoshor
Copy link
Author

edoshor commented Mar 22, 2020

a little helper to list known hosts

$> cat ~/.ssh/known_hosts | cut -d ' ' -f 1 | cut -d ',' -f 1 | awk -F: '{gsub("\\[|\\]","",$1); if ($2){print "-h " $1 " -p " $2}else{print "-h " $1}}' | sort > ssh_hosts.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment