expect脚本批量执行交互操作
#!/bin/bash
#ssh 连接慢的解决方法
#/etc/ssh/sshd_config 修改 UseDNS为no ,UsePAM yes,重启sshd服务
function print_red(){
echo -e "\e[1;31m $* \e[0m"
}
function print_green(){
echo -e "\e[1;32m $* \e[0m"
}
function print_yellow(){
echo -e "\e[1;33m $* \e[0m"
}
function print_blue(){
echo -e "\e[1;34m $* \e[0m"
}
function print_red2(){
echo -e "\e[1;35m $* \e[0m"
}
function print_cyan(){
echo -e "\e[1;36m $* \e[0m"
}
function print_white(){
echo -e "\e[1;37m $* \e[0m"
}
#需要在脚本同目录放一个 hosts_in.txt文件 里面格式 “IP|password”,一行一个记录
for host in `cat hosts_in.txt`
do
ip=`echo $host|awk -F "|" '{print $1}'`
pw=`echo $host|awk -F "|" '{print $2}'`
print_yellow "=============================================================> $ip|$pw"
expect <<EOF
set timeout -1
spawn ssh root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"*password:*" { send "$pw\r" }
}
expect "]#" { send "useradd agent\n" }
expect "]#" { send "echo 'agent'|passwd agent --stdin\r" }
expect "]#" { send "cd /home/agent;curl http://x.x.x.x/file/install.sh -o ./install.sh\r"}
expect "]#" { send "exit\r"}
expect eof
EOF
done