一、安装expect
yum install -y expect
二、简单了解expect
语法结构
spawn shell #命令程序
expect #"捕获到shell 命令程序执行之后输出的字符串"
send #"发送给 shell 命令程序的字符串"
在命令行直接输入 expect 可以进入 expect 程序的解释器终端
[root@server ~]# expect
expect1.1> spawn echo "hello" # 发送一条 shell 命令, 这里是指 echo "hello"
spawn echo hello
1490
expect1.2> expect "hello" # 捕获这个字符串,只要包含这个字符串就可以
hello
expect1.3> send "yes\n" # 发送一个字符串 "\n" 就是相当于按下回车键
expect1.4> expect off # 结束这次捕获
yes
expect1.5>
三、在脚本中应用
示例:
#自动生成密钥对的函数
ssh_keygen() {
/usr/bin/expect<<EOF # 开始 expect 解释器程序
set timeout 30 # 设置捕获字符串后,期待回复的超时时间
spawn ssh-keygen
# 开始进连续捕获
expect {
".ssh/id_rsa)" { send "\n"; exp_continue }
#exp_continue : 继续进行捕获,不退出expect程序
"Overwrite (y/n)?" { send "y\n"; exp_continue }
"no passphrase):" { send "\n"; exp_continue }
"again:" { send "\n"; exp_continue }
}
EOF # 结束 expect 解释器程序
}