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.
Expect is built on Tcl (Tool Command Language), but you only need to know a few key commands to get started:
spawn: Starts the process or command you want to automate.expect: Waits for specific output from the command.send: Sends a response or input to the command.interact: Allows the user to interact manually after the automation.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.
ssh_login.exp.bash
chmod +x ssh_login.exp
bash
./ssh_login.exp
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.
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"Expect can log the session output using the log_file command:
log_file output.logThis logs all output to output.log.
You can let the user take control after automated commands:
send "top\r"
interactThe script switches to manual control, allowing the user to interact with the top command.
scp or rsync.This should give you a strong foundation to start coding with Expect for automating command-line interactions!