All Snippets
Script to add ssh key to all your servers
Use this single bash script to place your ssh keys to remote server using ssh-copy-id
This is a basic script that I've been using for about 5 years now. Pretty easy to work with it. Make sure you have a file servers.txt in path ~/Documents/servers-list or change the path. Remember this script will always need your password to make an entry to a server. So it's frustrating for the first time.
Script
bash
| 1 | #!/bin/bash |
| 2 | for ip in `cat ~/Documents/servers-list/servers.txt`; do |
| 3 | echo "trying copy key to $ip" |
| 4 | ssh-copy-id -i ~/.ssh/for-servers.pub $ip |
| 5 | done |
Because now I have 100s of server, i need something better. So, here's v2 which needs a password single time.
Just make sure you have sshpass installed.
bash
| 1 | sudo apt install sshpass |
Script v2
bash
| 1 | #!/bin/bash |
| 2 | read -s -p "Enter SSH password: " SSHPASS |
| 3 | echo |
| 4 | while read -r ip; do |
| 5 | [[ -z "$ip" ]] && continue |
| 6 | echo "==> Copying key to $ip" |
| 7 | SSHPASS="$SSHPASS" sshpass -e ssh-copy-id \ |
| 8 | -i ~/.ssh/for-servers.pub \ |
| 9 | "$ip" |
| 10 | if [[ $? -eq 0 ]]; then |
| 11 | echo " SUCCESS: $ip" |
| 12 | else |
| 13 | echo " FAILED: $ip" |
| 14 | fi |
| 15 | done < ~/Documents/servers-list/servers.txt |
| 16 | unset SSHPASS |