Created
March 21, 2020 17:28
-
-
Save edoshor/e34bdffa773ef88658f92299bb0a99fb to your computer and use it in GitHub Desktop.
A small utility to automate replacement of ssh key on servers
This file contains 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
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a little helper to list known hosts