linux: expect脚本

1. 概述

expect是一个用来实现自动交互功能的软件套件,是基于TCL的脚本编程工具语言,方便学习,功能强大

2. 使用背景

在执行系统命令或程序时,有些系统会以交互式的形式要求输出指定的字符串之后才能执行命令,如用户设置密码,一般都是需要手工输入2次密码,再如SSH登录的,如果没有做免密钥登录,第一次连接要和系统实现两次交互式输入

3. 安装

yum install expect

4. 自动交互工作流程

spawn启动指定进程—>expect获取期待的关键字–>send向指定进程发送指定字符–>进程执行完毕,退出结束

5. expect相关命令说明

5.1 spawn命令

语法:

spawn [选项] [需要自动交互的命令或程序]

说明:
在expect自动交互程序执行的过程中,spawn命令是一开始就需要使用的命令。通过spawn执行一个命令或程序,之后所有的expect操作都会在这个执行过的命令或程序进程中进行,包括自动交互功能,因此如果没有spawn命令,expect程序将会无法实现自动交互

5.2 expect命令

语法:

expect 表达式 [动作]

说明:
expect命令的作用就是获取spawn命令执行后的信息,看看是否和其事先指定的相匹配。一旦匹配上指定的内容就执行expect后面的动作,expect命令也有一些选项,相对用的较多的是-re,使用正则表达式的方式来匹配。

5.3 send命令

说明:
即在expect命令匹配指定的字符串后,发送指定的字符串给系统,这些命令可以支持一些特殊转义符号,例如:\r表示回车、\n表示换行、\t表示制表符等

5.4 exp_continue命令

让expect程序继续匹配

expect {
    "yes/no" {exp_send "yes\r";exp_continue}
    "*password" {exp_send "guoke123\r"}
}

5.5 send_user命令

send_user命令可用来打印expect脚本信息,类似shell里的echo命令

root@game scripts]# cat send_user.exp 
#!/usr/bin/expect
​
send_user "guoke\n"
send_user "youtiao.\t" #tab键,没有换行
send_user "what hao\n"#效果
[root@game scripts]# expect send_user.exp 
guoke
youtiao.    what hao

5.6 exit命令

exit命令的功能类似于shell中的exit,即直接退出expect脚本,除了最基本的退出脚本功能之外,还可以利用这个命令对脚本做一些关闭前的清理和提示等工作

6. expect程序变量

6.1 set普通变量

set 变量名 变量值

6.2 puts打印变量

puts $变量名

举例

[root@iZ2zedqr9yeos47fg4uor5Z expect]# cat test.exp
#!/usr/bin/expect
set password "123455"
puts $password
[root@iZ2zedqr9yeos47fg4uor5Z expect]# ./test.exp
123455
[root@iZ2zedqr9yeos47fg4uor5Z expect]#

6.3 特殊变量

(1) 在expect里也有与shell脚本里的$0、$!、$#等类似的特殊参数变量,用于接收及控制expect脚本传参
(2) 在expect中$argv表示参数数组,可以使用[lindex $argv n]接收expect脚本传参,n从0开始,分别表示第一个[lindex $argv 0]参数、第二个[lindex $argv 1]参数

[root@iZ2zedqr9yeos47fg4uor5Z expect]# cat test2.exp
#!/usr/bin/expect
set file [lindex $argv 0]
set id [lindex $argv 1]
set host [lindex $argv 2]
puts "$file\t$id\t$host\n"
send_user "$file\t$id\t$host\n"
[root@iZ2zedqr9yeos47fg4uor5Z expect]# ./test2.exp test.log 1 192.168.1.1
test.log        1       192.168.1.1

test.log        1       192.168.1.1
[root@iZ2zedqr9yeos47fg4uor5Z expect]#

(3) 除了基本的位置参数外,expect也支持其他的特殊参数,例如:$argc表示传参的个数,$argv0表示脚本的名字

6.4 if条件语句

if {
    
    条件表达式} {
    
    
    指令
}if {
    
    条件表达式} {
    
    
    指令
} else {
    
    
    指令
}

if关键字后面要有空格,else关键字前后都要有空格,{条件表达式}大括号里面靠近大括号出可以没有空格,将指令括起来的起始大括号”{“ 前要有空格

[root@game scripts]# cat test3.exp 
#!/usr/bin/expectif {
    
     $argc != 3 } {
    
    
    send_user "usage:expect $argv0 file id host\n"
    exit
}set file [lindex $argv 0]
set id [lindex $srgv 1]
set host [lindex $argv 2]
puts "$file\t$id\t$host\n"#效果
[root@game scripts]# expect test3.exp 
usage:expect test3.exp file id host

6.5 eof/timeout关键字

(1)eof(end-of-file文件结尾):关键字用于匹配结束符
(2)timeout:控制时间,expect超时等待的时间,默认是10s

7. 附录

参考资料:https://zhuanlan.zhihu.com/p/192470248

猜你喜欢

转载自blog.csdn.net/qq_39198749/article/details/127322064
今日推荐