Monday, February 25, 2008

Expect - Automating Command line tools

Automating command line (CLI) tasks are always challenging for GUI automation tools. In my previous company, I used to use EXPECT for this kind of tasks. You can use telnet utility or Expect scripts to do this. I used EXPECT with Silktest. Expect is having a feature, you can feed the input based on the previous command's result. You can take baseline and compare with the current result.

You can connect with different operating Systems by expect scripts. It is developed as a package with Perl and Tcl/Tk. Three commands are central to the power of Expect. They are send, expect and spawn . The send command sends strings to a process, the expect command waits for strings from a process, and the spawn command starts a process.

Important Links
EXPECT home page
Windows version of EXPECT is available here
Getting Started

Sample
Call your EXPECT script by an batch or shell script. There you can pass the data as arguments.

4test statement:
SYS_Execute ("{GetProgramDir ()}\runftp_twiceexp.bat
{GetProgramDir ()}\ {lsInput[1]} {lsInput[2]}}} {lsInput[8]}", lsOutput)

Sample EXPECT code:


-----------------------------------------
##!/usr/local/bin/expect -f
#
# Automation for Unix system
#
#To delete the files from outbox table.
#
# hub name, installation path name, mailbox name is required.
#
# Author: Palani Selvam
#

# Check expect version
exp_version -exit 5.0.3

# root user login details
set username "root"
set upass "myrootpwd"

#super user login details
#set superuser "su"
#set supass "g0india"

#client,mailbox details
set pesetup_path "/opt/comp/pal_pnr"
set peclient "testhub"
set pmailbox "test_auto"

set timeout 10

#Start Telnet session
#spawn telnet jaguar

spawn telnet
expect "telnet>"
#send "telnet\r"
send "open jaguar\r"
sleep 1

expect {
"ogin*" {
# In case login is "Login or login"
send "$username\r"
sleep 1
}
timeout {
send_user "connection has timed out.\r\n"
exit
}
}
expect {
"assword*" {
# In case password is "Password or password"
send "$upass\r"
sleep 5
}
timeout {
send_user "password field has timed out.\r\n"
exit
}
}

# Partner or hub
expect {
"#*" {
send "cd $pesetup_path/data/stpush\r"
sleep 5
send "cd $peclient/$pmailbox/outbox\r"
sleep 4
send "ls -ltr *\r"
sleep 5
}
timeout {
send_user "Super user login has failed.\r\n"
exit
}
}

expect {
"rw*" {
send "cd completed\r"
sleep 2
send "rm *\r"
sleep 2

send "cd ../failed\r"
sleep 2
send "rm *\r"
sleep 2

send "cd ../partial\r"
sleep 2
send "rm *\r"
sleep 2

send "cd ../pending\r"
sleep 2
send "rm *\r"
sleep 2

send "cd ../retry\r"
sleep 2
send "rm *\r"
sleep 2
#puts "All files are deleted in outbox table.\r\n"
}
timeout {
send_user "Files are not existing in outbox table.\r\n"
exit
}
}

#To exit from the telnet
send "exit\r"
sleep 2
send "exit\r"

#Close the session
expect eof
-----------------------------------------

No comments: