Install 'expect' to control interactive UNIX apps

Nov 26, '02 08:54:08AM

Contributed by: loekjehe

The UNIX program expect is a tool for automatic interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc. expect is also useful for testing these same applications. Expect reads the output from interactive applications, allowing scripts to act based on the contents of that output.

With this very handy tool, you can easily create scripts that act on resulting output from commands. I created a cron job as an ordinary user calling a script to repair the privileges on my root disk (for which you must have root access). You might also create a root cron job for this, but I used this example to show you how to script root commands as an ordinary user. The script will insert your root password automatically when it is prompted for this!

This is what to do:

  1. Install Expect through fink (type "fink install expect").

  2. Create a script called repairprivsboot (with joe or vi or emacs), with the following text (give it u+rx permissions):
    #!/sw/bin/expect -f
    spawn ssh -2 -l yourname 12.34.56.78
    expect "yourname@12.34.56.78's password:"
    send "yourpassword\r"
    expect "yourname%"
    send "sudo diskutil repairPermissions / \r"
    expect "password:"
    send "yourpassword\r"
    set timeout 240
    expect "volume."
    You must replace "yourname" with the name of your root login account, 12.34.56.78 with your ip number and "yourpassword" with your root password. Of course, you must have ssh enabled to be able to login with ssh into your superuser account. The script will wait for the literal output that is in the "expect" lines, so you might have to check if this output is the same on your system.

  3. create a cron job as ordinary user with "crontab -e" using vi, adding the following line:
    40    20    *    *    *    theFullPath/repairprivsboot
    Replace theFullPath with the full path to the script. This line will start the root disk repair of privileges every evening at fourty minutes past eight.
Please note there is a certain security risk here, because your root password in the script is "in the open" i.e. unencrypted. So please check the privileges and rights of this script file to ensure that no others can read it.

[Editor's note: I tried to compile expect from the source, and I'm sure it's possible, but there are some dependencies (tcl) that must be installed first, and I believe the configure script needs to be edited a bit to account for the hostname ... both of which are beyond my skill set. Using fink is definitely the easy way to get 'expect' running.]

Comments (4)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20021126055408382