最後更新: 2023-09-28
介紹
expect offers a way to control interactive applications which require user input to continue.
Expect uses Tcl (Tool Command Language)
Install
dnf install expect -y
expect -v
expect version 5.45.4 # R8
Usage
expect [options] [commands/command file]
options
-f Specifies a file to read from.
-c Specifies the command to execute before the script.
Run by script
#!/usr/bin/expect -f
主要 Syntax
- spawn Creates a new process.
- send Sends a reply to the program.
- expect Waits for output.
- interact Enables interacting with the program.
Example
[1] expect
Syntax:
expect patterns|keyword action
Pattern:
- Default: string matching is glob-style patterns (*, ?)
- "-ex" flag causes the pattern to be matched as an "exact" string.
- "-re" flag forces the string to be interpreted as a regexp-style pattern.
keyword:
- eof # The default eof action is "return" => 返回 interact
- timeout # Default timeout is 10 seconds
- default # corresponding body is executed upon either timeout or end-of-file
input.sh
#!/bin/bash read -p "Please input a number: " ANSWER echo "You input $ANSWER"
ans.sh
#!/usr/bin/expect -f
expect "Please input"
send "1\r"
# 必須加, 否則見會見唔到 "You input $ANSWER"
expect eof
Notes
Script 多數以 "expect eof" 或 "interact" 結尾.
"expect eof" 的功能: 等待 EOF condition
當沒有 "expect eof" , 那 script 就會在 send 之立即中止
[2] timeout & set 的應用
Default timeout is 10 seconds
#!/usr/bin/expect -f set timeout 3 set pw MYPW spawn ssh -p 22 USER@SERVER_IP expect { "yes/no" { send "yes\r";exp_continue } "password:" { send "$pw\r" } } interact
[3] User input
set user [lindex $argv 0]
set password [lindex $argv 1]
expect auto_login.exp user_name some_password
[4] msg to user
puts vs send_user
if you're using log_file, send_user will make it into the logfile, whereas statements sent with puts do not.
puts automatically appends a newline and send_user does not.
send_error[-flags] string
[5] log
send_log [--] string
log_file[args] [[-a] file]
will record a transcript of the session in the file.
By default, the log_file command appends to old files rather than truncating them
To truncate files, use the -noappend flag.
[6] Other
sleep seconds