Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active July 1, 2022 01:07
Show Gist options
  • Save eusonlito/aa279cfba24fa52599f6 to your computer and use it in GitHub Desktop.
Save eusonlito/aa279cfba24fa52599f6 to your computer and use it in GitHub Desktop.
Adds new SSH Keys to multiple servers and checks the connection. SSH Keys will not be duplicated if exists.
#!/bin/bash
# Install: Download and add execution permissions
#
# Usage: ./add-keys-to-servers "current-private-key-to-connect" "new-private-key-to-add" "servers.list"
#
# First parameter must be the current available key to connect to servers
# Second parameter must be the new key to add to servers
# Third parameter must be the servers list (One line for server with format: hostname,port)
error() {
echo ''
echo $1
echo ''
exit 1
}
if [ "$1" == "" ] || [ ! -f "$1" ]; then
error '[REQUIRED] First parameter must be the current available key to connect to servers'
fi
if [ "$2" == "" ] || [ ! -f "$2" ] || [ ! -f "$2.pub" ]; then
error '[REQUIRED] Second parameter must be the new key to add to servers'
fi
if [ "$3" == "" ] || [ ! -f "$3" ]; then
error '[REQUIRED] Third parameter must be the servers list (One line for server with format: hostname,port)'
fi
servers=$(cat "$3")
current="$1"
new="$2"
key=$(cat "$new.pub")
for server in $servers; do
echo ''
echo 'ADDING KEY TO '$server
host=$(echo $server | awk -F, '{print $1}')
port=$(echo $server | awk -F, '{print $2}')
ssh -i "$current" -o StrictHostKeyChecking=no -o ConnectTimeout=10 -p $port $host '
if [ ! -f .ssh/authorized_keys ] || [ "$(grep "'$key'" .ssh/authorized_keys)" = "" ];
then $(echo "'$key'" >> .ssh/authorized_keys);
fi
'
echo 'CHECKING CONNECTION '$server
ssh -i "$new" -o BatchMode=yes -o ConnectTimeout=10 -p $port $host echo "CONNECTION OK" 2>&1
done
echo ''
echo 'FINISH'
echo ''
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment