实现真正的自动化,expect脚本语言使用
expect中的几个重要句子:
expect的核心是spawn expect send set
spawn 调用要执行的命令
expect 等待命令提示信息的出现,也就是捕捉用户输入的提示:
send 发送需要交互的值,替代了用户手动输入内容
set 设置变量值
interact 执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。
expect eof 这个一定要加,与spawn对应表示捕获终端输出信息终止,类似于if....endif
set timeout -1表示无超时时间
set timeout 10表示超时时间为10秒
注意:expect脚本必须以interact或expect eof结束,执行自动化任务通常expect eof就够了。
------------------------------------------------------------
实例:ssh 远程登录,发送reboot指令
vim reb.expect
#!/usr/bin/expect -f
set timeout 10
set username root #定义变量
set hostname 192.168.137.28
set password redhat
spawn ssh "$username@$hostname" #执行命令
expect { #捕捉信息的提示,以进入下一步的命令输入
"yes/no" {send "yes\r";exp_continue} #exp_continue表示继续下一步
"password:" {send "$password\r"}
}
expect "#"
send "shutdown -r now\r" #重启命令
send "exit\r" #退出登录
expect eof #终止expect的捕捉
exit------------------------------
实现停留在远程主机:
#!/usr/bin/expect -f
set timeout 10
set username root
set hostname 192.168.137.28
set password redhat
spawn ssh "$username@$hostname"
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "$password\r"}
}
expect "#"
send "ll ; df -hT\r"
#send "exit\r"
#expect eof
interact #执行完后保持交互的模式,此时可以手工操作
exit------------------------------------------------------------
在脚本中引用expect脚本:expect -c ""
vim reb.sh
#!/bin/bash
username="root"
hostname="192.168.137.28"
password="redhat"
expect -c " #-c 实现调用
##注意凡是-c后调用的内容,如果带有""双引号的话,必须用\进行转义,否则报错
set timeout 10
spawn ssh \"$username@$hostname\"
expect {
\"yes/no\" {send \"yes\r\";exp_continue}
\"password:\" {send \"$password\r\"}
}
expect \"]#\"
send \"ll\r\"
interact
exit
"--------------
expect -c <<EOF
.......
EOF
使用这个种方式的时候,不能停留在远程主机上
本文出自 “天道酬勤” 博客,请务必保留此出处http://luzhi1024.blog.51cto.com/8845546/1660276
原文地址:http://luzhi1024.blog.51cto.com/8845546/1660276