Often times you have to interact with programs that require passwords or some other input from the user. For security purposes, some programs will not read from stdin so you have to be creative. Enter "expect". Expect is a program written in Tcl that allows you to mimic a conversation you’d have with any number of programs. There are lots of examples on the web, but I wanted to put up a really simple one just to get the picture across of how it can be used.
Let’s consider this simple python program, foo.py:
input = raw_input("Enter:") print "You entered %s" % input
Running python foo.py will print “Enter:” to the command line and wait for the user to enter something followed by hitting “Enter”. It will then print out what the user entered, a simple echo program. Let’s drive this programatically using expect (aside: yes, I know you don’t need expect to something like this).
Here’s our expect script:
#!/usr/bin/expect spawn python foo.py expect "Enter:" send "Repustater" expect eof
Line by line:
- Indicates which script should be used to execute the code that follows
- spawn starts a new program. So we’re running our python program as we normally would
- OK here’s the magic; we’re saying that we expect the string “Enter:” to be returned by the spawned program.
- Now we’re saying send the string “Repustater” (watch that carriage return, we need it otherwise python will just wait) to the waiting python process.
- This line means to wait for the program we spawned to finish before we exit the expect script.
There you have it, a really simple intro how to use expect to expect what you expect. There is so much you can do with expect and it’s left to the reader to go out and discover all these nifty features. It really comes in handy when you want to interact with programs that require passwords but for security purposes, won’t read from stdin.