expect

expect is an automation tool for automating interactive tasks. πŸ€–. For instance, we could automatically enter credentials to a command.

$ sudo apt-get install expect

We will define a text/pattern that we are expecting (ex: "login: "). When it is found, we will determine which text to send.

We often create a .exp file with all commands:

$ cat myscript.exp
#!/usr/local/bin/expect -f

...
$ ./myscript.exp

Expect Basics

Basic Usage

We can use spawn to start a process:

spawn some_command
spawn ./some_script

We pass to expect the text we are waiting for.

expect "login: "
expect -exact "login: "
expect eof

And then we define what text we are injecting:

send "username\r"
send -- "username\r"

⚠️ The process is only started when we call send. The process is terminated if there is no more expect.

➑️ Use interact to execute manual tasks.

Variables

You can define variables using set:

set varname varvalue
spawn echo "$varname"

Multiple processes

When a process is started, the $spawn_id variable is set. It is used by the following expect or send calls to determine which process they are working on. We can set it manually.

# current=processA
spawn processA            
set processA_id $spawn_id
spawn processB
# current=processB
set processB_id $spawn_id
# current=processA
set spawn_id $processB_id

Import Script

You can use source to import another script:

source ./xxx.exp

πŸ‘» To-do πŸ‘»

Stuff that I found, but never read/used yet.

  • autoexpect my_script