#!/bin/bash
###########################################################################
# discription:批量想目标主机发送远程命令或传输文件
# author:frogchou
# time:20181219
###########################################################################

rpm -qa | grep expect > /dev/null
if [ ! $? == 0 ];then
	yum install -y expect > /dev/null
	if [ ! $? == 0 ];then
		echo "安装expect失败，退出。"
		exit -1
	fi
fi

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

runcmd(){
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 ${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
}


runfile(){
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 scp -r $1 ${hostinfo[1]}@${hostinfo[0]}:$2
		expect {
			"(yes/no)?"
				{
					send "yes\n"
					expect "password:" {send "${hostinfo[2]}\n"}
					}
			"password:"
				{
					send "${hostinfo[2]}\n"
				}		
			}
		expect eof
EOF
	done
}

main(){
	read -p "做什么?(1，执行命令；2，传输文件)：" var
	if [ $var -eq 1 ];then
		read -p "命令：" cmd
		runcmd $cmd
	elif [ $var -eq 2 ];then
		read -p "源文件路径：" srcpath
		read -p "目标文件路径：" dstpath
		runfile $srcpath $dstpath
	else
		clear
		main
	fi
}	

main


