Echoing

Another mode that is frequently changed is echoing. By default, the terminal driver echoes printable characters typed at the keyboard. If a script needs to query for, say, a password, the echoing should be disabled. The following two commands disable and re-enable echoing.

stty -echo                    ;# disable echo
stty echo                    ;# enable echo

Here is an archetypal procedure to query the user for a password:

proc getpass {} {
    set timeout −1
    stty -echo
    send_user "password: "
    expect_user -re "(.*)\n"
    send_user "\n"
    stty echo
    return $expect_out(1,string)
}

When called, getpass returns the password as its return value. Inside, you can see two stty commands surround the expect_user that waits for the password. Notice how the first stty is done before the prompt. This guarantees that user input cannot possibly be echoed no matter how fast it starts arriving after the prompt.

After expect_user returns, the cursor remains at the end of the prompt. Even though the user pressed return, nothing happens because echoing is disabled. It is important to give the user feedback that the line was accepted. Hence a \n is printed. This simulates the effect of echoing being disabled just for the bare password. This is not a problem specific to Expect. Any password reading routine has to do the same thing.

In Chapter 7 (p. 175), I presented a script called su2 which spawned an su process to reexecute a command and then leave the user in a root shell. As I originally defined it, the password was entered as a parameter ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.