‘Expect’ as an administration tool
This is an article that I had posted in my livejournal on 6th-May-2006 06:58 pm. I’m trying to migrate the most valuable stuff to wordpress.
Last time we saw how to execute those special system tools(ssh, ftp, su, …) by providing the password through PTYs. But, the problem is that its not easy or ideal at all to write a C program to do such system maintenance or automation tasks. Also, if we need to process the output of the running child program and respond it with dynamic inputs, the task becomes very complicated. Then, the obvious guess would be… right, a script. Today, we’re going to see how ‘Expect’ can be used to do our task with ease.
Expect can be thought of as a tool which can run other programs in a PTY with the knowledge of what to expect from the child program. ie, Expect can be told how to behave towards the child program for its various outputs. And its being done through a script similar to Tcl. Unfortunately, I don’t know Tcl at all, but certainly know how to use expect for my needs. So here’s the code that does what we required when we wrote the last C program – ptymagic.c:
#!/usr/bin/expect
spawn [lrange $argv 0 0] [lrange $argv 1 $argc]
expect {
“Password:” {
expect_user -re “(.*)\n”
send_user “\n”
send “$expect_out(1,string)\r”
exp_continue}
}
Suppose you name the file as ptymagic, and give execute permission for the same, test it as we did previously:
echo “Your_Root_Password” | ./ptymagic su -c “cat /etc/shadow”
May be it’ll seem slow, but hey, we are here to write maintenance script for the system and not any scientific supercomputing simulations…
best of luck…