shell脚本需要交互的地方可以使用here文档是实现,但是有些命令却需要用户手动去就交互如passwd、scp
对自动部署免去用户交互很痛苦,expect能很好的解决这类问题。
expect的核心是spawn expect send set
spawn 调用要执行的命令
expect脚本必须以interact或expect eof结束,执行自动化任务通常expect eof就够了。
expect编写语法,expect使用的是tcl语法。
反斜线符号是用来引用特殊符号. 例如:n 代表换行. 反斜线符号也被用来关闭”$”符号, 引号,方括号和大括号的特殊含义
expect使用实例
1。首先确认expect的包要安置。
#rpm -qa | grep expect
如果没有则需要下载安装,
#yum install expect
2.安装完成后,查看expect的路径,可以用
#which expect
/usr/bin/expect
#!/usr/bin/expect -f //这个expect的路径就是用which expect 查看的结果
spawn su – nginx //切换用户
expect “password:” //提示让输入密码
send “testr” //输入nginx的密码
interact //操作完成
4.确定脚本有可执行权限
chmod +x autosu.sh
5.执行脚本 expect autosu.sh 或 ./autosu.sh
expect常用脚本
登陆到远程服务器
#!/usr/bin/expect
set timeout 5
set server [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
spawn ssh -l $user $server
expect {
“(yes/no)” { send “yesr”; exp_continue }
“password:” { send “$passwdr” }
}
expect “*Last login*” interact
scp拷贝文件
#!/usr/bin/expect
set timeout 10
set host [lindex $argv 0] //第1个参数,其它2,3,4参数类似
set username [lindex $argv 1]
set password [lindex $argv 2]
set src_file [lindex $argv 3]
set dest_file [lindex $argv 4]
spawn scp $src_file $username@$host:$dest_file
expect {
“(yes/no)?”
{
send “yesn”
expect “*assword:” { send “$passwordn”}
}
“*assword:”
{
send “$passwordn”
}
}
expect “100%”
expect eof
done
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/216094.html原文链接:https://javaforall.net
