Skip to content

Expect cheatsheet

Examples

su

Execute command as other user using expect and su commands.

Warning: Hard-coding passwords in the scripts is a bad security practice.

#!/usr/bin/expect

set timeout 20
spawn su - USER -c id
expect "Password:"
send "PASSWORD\r"
expect "% "

One-liner

expect -c 'set timeout 20; spawn su - USER -c id; expect "Password:"; send "PASSWORD\r'; expect "% "'

Supply command as an argument to expect script

#!/usr/bin/expect

set timeout 20
set cmd [lindex $argv 0]

spawn su - USER -c $cmd
expect "Password:"
send "PASSWORD\r"
expect "% "

Command as an argument, username and password in variables

#!/usr/bin/expect

set timeout 20
set cmd [lindex $argv 0]
set user "admin"
set password "password"

spawn su - $user -c $cmd
expect "Password:"
send "$password\r"
expect "% "

ssh

#!/usr/bin/expect

set timeout 20

spawn ssh USER@HOST
expect "password:"
send "PASSWORD
"
interact