Expect is a powerful automation tool used to automate interactive command-line applications, such as SSH, Telnet, or any program that prompts the user for input. It allows you to script responses to prompts, enabling hands-off automation.

1. Basics of Expect

Expect is built on Tcl (Tool Command Language), but you only need to know a few key commands to get started:

2. Example: Automating an SSH Login

This script automates an SSH login process:

#!/usr/bin/expect

set timeout 10
spawn ssh user@hostname
expect "password:"
send "your_password\r"
expect "$ "
send "ls -l\r"
expect "$ "
send "exit\r"

Explanation: - set timeout 10: Sets a timeout of 10 seconds for each command. - spawn ssh user@hostname: Starts the SSH process. - expect "password:": Waits for the prompt "password:". - send "your_password\r": Sends the password followed by a carriage return (\r). - expect "$ ": Waits for the shell prompt. - send "ls -l\r": Sends the ls -l command. - send "exit\r": Logs out from the SSH session.

3. Running the Script

4. Handling Multiple Prompts

You can use multiple expect commands to handle different prompts:

#!/usr/bin/expect

spawn scp file.txt user@hostname:/path
expect {
    "password:" {
        send "your_password\r"
    }
    "continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
}

Explanation: - expect {}: Uses a block to handle different possible prompts. - exp_continue: Continues expecting more prompts after handling one.

5. Using Variables in Expect

You can use variables to make your scripts more dynamic:

#!/usr/bin/expect

set user "username"
set host "hostname"
set pass "password"

spawn ssh $user@$host
expect "password:"
send "$pass\r"
expect "$ "
send "uptime\r"
expect "$ "
send "exit\r"

6. Logging Output

Expect can log the session output using the log_file command:

log_file output.log

This logs all output to output.log.

7. Interacting with the User

You can let the user take control after automated commands:

send "top\r"
interact

The script switches to manual control, allowing the user to interact with the top command.

Practical Uses of Expect

This should give you a strong foundation to start coding with Expect for automating command-line interactions!