Skip to content

Instantly share code, notes, and snippets.

@danf0rth
Last active September 17, 2021 14:50
Show Gist options
  • Save danf0rth/9b29f8d25ef3204ea0bb9dff00bd6eb2 to your computer and use it in GitHub Desktop.
Save danf0rth/9b29f8d25ef3204ea0bb9dff00bd6eb2 to your computer and use it in GitHub Desktop.
Copy public key to multiple servers
1.2.3.4 secret-pass
123.14.144.42 another-pass
#!/bin/bash
# Usage: ssh-copy-multiple.sh file_with_hosts.txt key_1.pub key_2.pub .. key_n.pub
filename=$1
keys=${@:2:10}
echo "reading file: ${filename}"
while read line; do
read server password <<< $line
## deleting server from known hosts
if grep $server ~/.ssh/known_hosts;
then
echo "$server found in known hosts, deleting...";
ssh-keygen -R $server
else
echo "$server not found in known hosts..."
fi
for key_path in $keys; do
echo "uploading key: $key_path"
if [[ ! -z $password ]]
then
echo "password is not empty, trying to upload key via password..."
sshpass -p $password \
ssh-copy-id -f -i $key_path -o StrictHostKeyChecking=no root@$server 2>/dev/null
else
ssh-copy-id -f -i $key_path -o StrictHostKeyChecking=no root@$server 2>/dev/null
fi
done;
done < $filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment