Thursday 28 March 2013

Expect - Linux Automation Tool: Part 2

Hi all,
In this post I'll try to explain about spawn, interact and using command line arguments.. In last post, I told you that - expect, send, spawn and interact are some of the most imp commands in expect.

Lets see what they're in single line definition:

  • Expect : Expect command defines the string that is expected from the process. For example when we do ssh, it prompts for password as "password: ". Here "password: " is expected string.


  • Send : Send command tell us what is the value we want to send to the process, in this case of ssh, our password. Send feeds the value as if it's typed by any human.


  • Spawn : Spawn specifies the [interactive] command we want to execute, say "ssh user@server". Syntax is : "spawn command_to_be_executed"


  • Interact : Interact is used to pass the control to the spawned process. Interact returns the control to our script after the spawned process ends.


Command line arguments :
Command line args as we all know are the values/ arguments that we send to our script at the time of execution. Expect stores command line args in list.

Enough of theory, time to code. As Linus Torvalds has said, Talk is dirty. Show me the code.


  1. #!/usr/bin/env expect
  2. #####################################################
  3. # Filename:     su.exp                                 
  4. # Description:  Script to automate the granting of SU shell using expect
  5. # Author:       RahulB                         
  6. #####################################################
  7. if {[llength $argv] == 0} {
  8.         puts "Usage: ./su password"
  9.         exit 1
  10. }
  11. set passwd [lindex $argv 0]
  12. spawn sudo su -
  13. expect {
  14.         "password" {send "$passwd\r"}
  15. }
  16. interact



Now lets inspect the code.


  • In this we first check if the command line argument is given or not, if not we print error using puts and exit w/ error code 1.


Note: We've checked the length of list argv using the llength (yeah no typo, it stands for list length). Or we can use $argc. Both are same.


  • Then we declare the variable passwd. Variables are declared using "set". We read the first element of our list and stores it into passwd.


  • Then we invoke our interactive command, i.e "sudo su -" using spawn. Then the string "password: " is expect. When this string appears, we send our password, stored in variable followed by "\r".


Please Note: we're sending "\r", not "\n" because former is Carriage Return and latter is new line/ line feed. So it's like we entered our password and pressed Enter key.


  • At last we use interact to pass the control to the shell.


  • Save it as "su.exp" and make it executable by 

chmod +x su.exp


  • And run it as

./su.exp your_password

Hope it was easy and simple. Suggestions and rectifications invited.
Cheers.

No comments:

Post a Comment