6 Expect Script Examples To Expect The Unexpected
6 Expect Script Examples To Expect The Unexpected
6 Expect Script Examples To Expect The Unexpected
Make sure to install expect packages on your system, as it does not get
installed by default. Once installed, youll see the expect interpreter as
/usr/bin/expect. Generally, expect script files has .exp as extensions.
#!/usr/bin/expect
expect "hello"
send "world"
#!/usr/bin/expect
set timeout 10
expect "hello"
send "world"
#!/usr/bin/expect
set timeout 20
spawn "./addition.pl"
interact
$ ./user_proc.exp
spawn ./addition.pl
Result : 35
In case, if you have written the code without interact command, then the
script would exit immediately after sending the string 23\r. Interact
command does the control, hands over the job to the addition process, and
produces the expected result.
On the successful matching of string expect returns, but before that it stores
the matched string in $expect_out(0,string). The string that are received
prior plus the matched string are stored in $expect_out(buffer). The below
example shows you the value of these two variable on match.
#!/usr/bin/expect
set timeout 20
spawn "./hello.pl"
expect "hello"
interact
The hello.pl program just prints only two lines as shown below.
#!/usr/bin/perl
$ ./match.exp
spawn ./hello.pl
Perl program
hello world
hello>
match : <hello>
Expect allows you to pass the password for the Linux login account from
the program, instead of entering the password on the terminal. In the below
program, su login is automated to login into desired accounts.
#!/usr/bin/expect
set timeout 20
spawn su $user
expect "Password:"
send "$password\r";
interact
spawn su guest
Password:
guest@localhost $
After running the above script, it logged into the guest user account from
bala user account.
set timeout 20
expect "Password:"
send "$password\r";
interact
Password:
root@host2 #