yum install expect -y
# 1.生成密钥对
#!/usr/bin/expect
spawn ssh-keygen -t rsa -b 2048
expect {
"id_rsa):" {
send "\r"
expect "passphrase):" {
send "\r"
expect "again:" {
send "\r"
}
}
}
}
expect eof
# 2.烦人的mysql初始化
#!/bin/bash
mysql_pwd="`pwgen -cny 20 1`"
/usr/bin/expect <<-EOCCCCCC
spawn /usr/bin/mysql_secure_installation
expect "Enter current password for root (enter for none):"
send "\r"
expect "Set root password? "
send "Y\r"
expect "New password: "
send "${mysql_pwd}\r"
expect "Re-enter new password: "
send "${mysql_pwd}\r"
expect "Remove anonymous users?"
send "Y\r"
expect "Disallow root login remotely?"
send "Y\r"
expect "Remove test database and access to it?"
send "Y\r"
expect "Reload privilege tables now?"
send "Y\r"
expect eocccccc;
EOCCCCCC
echo ${mysql_pwd}
# 3.独立expect脚本模式,如下:
(expect支持命令行参数,如:set option [lindex $argv 0](获得第一个参数存到变量option中,参数是的index是从0开始计算的)
#!/usr/bin/expect
#超时时间
set timeout 20
log_file test.log
log_user 1
#参数传入
set hostname [lindex $argv 0]
set password [lindex $argv 1]
#追踪命令
spawn ssh root@$hostname
#捕捉信息并且匹配,免交互执行
expect {
"Connection refused" exit
"service not known" exit
"(yes/no)"
{send "yes\r";exp_continue}
"*password"
{send "$password\r"}
}
#控制权交给控制台执行
interact
exit