Created
October 21, 2024 07:49
-
-
Save abu-raihan-ddclbd/a03460f0b5a8d19e90985bf78d6096d5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/bin/bash | |
| # Step 1: Prompt the user to optionally provide a password upfront | |
| read -sp "Enter password (press Enter to skip if you want to input manually during execution): " PASSWORD | |
| echo "" | |
| # Define servers | |
| servers=( | |
| "172.16.51.40" | |
| "172.16.51.86" | |
| "172.16.51.99" | |
| "172.16.51.120" | |
| "172.16.51.80" | |
| "172.16.51.6" | |
| "172.16.51.23" | |
| "172.16.51.116" | |
| ) | |
| # Step 2: Add the servers' SSH keys to the known_hosts file using ssh-keyscan | |
| for server in "${servers[@]}"; do | |
| echo "Scanning SSH key for $server and adding to known_hosts..." | |
| ssh-keyscan -H $server >> ~/.ssh/known_hosts | |
| done | |
| # Step 3: Loop through servers to copy SSH key | |
| for server in "${servers[@]}"; do | |
| if [[ -z "$PASSWORD" ]]; then | |
| # If no password was provided, allow manual input during ssh-copy-id operation | |
| echo "No password provided, you will need to enter the password manually for $server." | |
| ssh-copy-id root@$server | |
| else | |
| # If password was provided, use sshpass to automatically pass the password | |
| echo "Copying SSH key to $server using provided password..." | |
| sshpass -p "$PASSWORD" ssh-copy-id -i /root/.ssh/id_ed25519 -o StrictHostKeyChecking=no root@$server | |
| fi | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment