Thursday 28 March 2013

Expect - Linux Automation Tool: Part 1

Introduction:

Automation of tasks is one of those bless that saves hell lot of time of any sysAdmin. Mostly automation is done through scripting. And in case of Linux, through bash or Tcl scripts. Scripts come handy in the case of tasks, which are repetitive or need to be done on a regular basis. But interacting with the application program that requires user's input, for example - partitioning, changing users' password, ssh, ftp, etc, is pretty time consuming. In this situation, "expect" is one such tool, that comes to rescue you.

What is Expect:

Expect is a program to control interactive applications. These applications interactively prompt and expect a user to enter keystrokes in response. By using Expect, you can write simple scripts to automate these interactions. And using automated interactive programs, you will be able to solve problems that you never
would have even considered before.
- Don Lines (Man behind Expect), in his book, "Exploring Expect"

So we can see using expect we can control the programs that require user inputs too. We'll soon see how. It is an extension to Tcl scripting language.

Some main commands:
  • spawn
  • send
  • expect
  • interact

We'll see how these commands work, by using a simple program:
Note: You might need to install expect, you can simply by "apt-get install expect".


  1. #!/usr/bin/env expect
  2. # hello.exp
  3. # Description: Hello world program in expect
  4. # Author: RahulB
  5. expect {
  6.         "hello" { send "world\n" }
  7. }
  8. exit 0


Now lets disassemble this, line by line..
1. First line is the shebang/ hashbang line that tells which interpreter to use.

2. Next 3 lines are the comment section tell us the info about code. Note that extension is .exp.

3. Next is the expect command. Expect command defines the string that is expected from the process. For example when we do ssh, it prompts for password as "password: ". So while writing writing a ssh code, we'll expect a "password: ".

4. In next line, we define what we are expecting or looking for, in this case "hello". and then there is send command, that tell us what is the value we can to send to the process, in this case hello.
Please Note: There are many other ways by which we can define this expect/send clause, I like this one. Matter of personal choice.

5. Last line returns 0 to show successful execution of script.

Cheers.
Thanks for reading. Please, leave your suggestions, etc in comments.

No comments:

Post a Comment