expect 的使用

Linux Shell

Posted by gomyck on November 2, 2023

安装

使用 yum apk apt-get 安装 expect 即可

语法

1
2
3
4
5
6
7
expect [选项] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]

-c:从命令行执行expect脚本,默认expect是交互地执行的
示例:expect -c 'expect "\n" {send "pressed enter\n"}'

-d:输出调试信息
示例:expect -d ssh.exp

expect 脚本中只能使用合法的语法, 不允许使用其他的 shell 语法:

1
2
3
4
5
spawn        启动新的进程
send         向进程发送字符串
expect       从进程接收字符串
interact     允许用户交互
exp_continue 匹配多个字符串时在执行动作后加此命令

expect eof 表示交互结束,退回到原用户 interact 会停留在目标用户

**expect eof 和interact 二者可以根据情况选一个作为结尾,一般我们使用 expect eof **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/expect

set arg1 [lindex $argv 0] # 接收参数
set arg2 [lindex $argv 1] # 接收参数
set ofile "result.txt" #保存结果的文件
set output [open $ofile "w"] #打开文件
set timeout 30 #设置超时
log_file expect.log #日志文件
spawn node-red admin hash-pw #启动子进程
expect {
  "Password:" {
    send "$env(MY_PASSWORD)\r"
    exp_continue # 这个是为了继续往下匹配 "其他情况:"
  }
  "其他情况:" {send "echo xxx && exit"}
}
set results $expect_out(buffer)
#保存结果到文件
puts $output $results
expect eof
1
2
3
expect << EOF
#expect 脚本
EOF