shell编程在完成我们的日常操作命令的时候常常会遇到要应答的情况出现;为了解决这个问题,我们来了解一下expect。(注意expect的语法在shell中并不能识别,可以用类似与cat的写法,后面会讲)
expect可以实现自动交互免密登陆操作。
语法结构
spawn 命令
expect 写捕获的语句(语句片段也行)
send 回应的内容
在脚本中可以这样写
/usr/bin/expect <<EOF #有点类似与cat的输入
set timeout 30 #等待30秒
spawn ssh-keygen #要执行的命令
expect {
"/.ssh/id_rsa):" {send "\n"; exp_continue}
"Overwrite (y/n)?" {send "y\n"; exp_continue }
"no passphrase):" {send "\n"; exp_continue}
"passphrase again:" {send "\n"; exp_continue}
}
EOF
捕获到字符串 ".ssh/id_rsa)" 后 发送字符串 "\n" 就是相当于按下回车键
exp_continue 意思是继续进行捕获,不退出 expect 程序
练习:
写一个脚本可以发送自动生成密钥和自动发送密钥建立连接