#!/bin/bash
###########################################################################
# discription:批量添加互信
# author:frogchou
# time:20181219
###########################################################################

if [ ! -f hostsinfo ];then
	echo "不存在hostsinfo文件！"
	echo "在脚本同目录增加hostsinfo文件，内容格式如下："
	echo " hostip	root	123456"
	echo " "
	exit -1
fi

#生成公钥
yum install -y expect
/usr/bin/expect <<EOF
spawn ssh-keygen
expect {
	"(/root/.ssh/id_rsa):"
		{ 
			send "\n"
			expect "(y/n)?" {send "yes \n"
				expect "(empty for no passphrase):" {send "\n"
					expect "again:" {send "\n"}
					}
				}
			expect "(empty for no passphrase):" {send "\n"
				expect "again:" {send "\n"}	
				}	
		}
}
expect eof
EOF

cat hostsinfo | while read line
	do
	count=0
	hostinfo=()
	for i in $line;
		do
		hostinfo[$count]=$i
		let count++	
		done
/usr/bin/expect <<EOF
spawn ssh-copy-id ${hostinfo[1]}@${hostinfo[0]}
		expect {
			"(yes/no)?"
				{
					send "yes\n"
					expect "password:" {send "${hostinfo[2]}\n"}
					}
			"password:"
				{
					send "${hostinfo[2]}\n"
				}		
			}
		expect eof
EOF
	done
