Automate ssh-copy-id with numbered hosts


Warning: count(): Parameter must be an array or an object that implements Countable in /home/fbsqlcom/public_html/youdidwhatwithtsql.com/wp-content/plugins/wp-codebox/main.php on line 31

Here’s a script I use to automate ssh-copy-id when I need to add a series of hosts using a incremental node number. For example…

prod-db-server001
prod-db-server002
prod-db-server003

and so on. The script uses expect to perform its work. To adjust this for your own purposes you simply need to change the SSH_USER variable, the number of hosts in the for loop and of course the hostname scheme. Once you execute the script you’ll enter your password once and ssh-copy-id will be performed for all the hosts in sequence.

#!/bin/bash
 
set -x;
 
export SSH_USER="admin"
read -s PASSWORD
export PASSWORD
 
for node in {1..91}; do
        if (( $node <= 9 )); then
                export HOST=hostname00${node}.domain.ch
        else
                export HOST=hostname0${node}.domain.ch
        fi;
 
    expect -c '
    set SSH_USER $env(SSH_USER)
    set HOST $env(HOST)
    set PASSWORD $env(PASSWORD)
    spawn ssh-copy-id $SSH_USER@$HOST
    expect {
        "continue" {
            send "yes\n";
            exp_continue
        }
        "assword:" {
            send "$PASSWORD\n";
        }
    }
    expect eof'
 
    echo "Done $HOST"
done;

Leave a Reply