Sending An SSH Key To Multiple SSH Hosts

The script below will first create an SSH public/private key pair on the current, main host. It will then get your username and prompt for your password allowing the root user to add your account to the destination servers. Note: you must have a root login on each host. The ping statement is used to check to see if the host is up so we don’t waste time. This script will then wait on stdin (via cat with no arguments) and write the ssh key-file (via the piped data) to the temp directory. It will then add the username, set the password, create a ssh directory and move the transferred key file to it. At the end, it will then give ownership to the specified username.

#!/bin/bash

ssh-keygen

u=`whoami`
read -s -p "Password: " pass

for x in {1..7}-{1..5}
do
	ping -c 1 -W 1 $x > /dev/null 2>&1
	if [ $? -eq 0 ]
	then
		tempkeyf='cat > /tmp/authorized_keys'
		makeuser='useradd '$u
		makepass='printf "'$pass'" | passwd --stdin '$u
		makesshd='mkdir /home/'$u'/.ssh'
		copykeyf='mv /tmp/authorized_keys /home/'$u'/.ssh/'
		ownevery='chown -R '$u' /home/'$u'/.ssh'
		cat ~/.ssh/id_rsa.pub | ssh root@$x "$tempkeyf ; $makeuser ; $makepass ; $makesshd ; $copykeyf ; $ownevery"
	fi
done

Sending An SSH Key To Multiple SSH Hosts

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s