Search code examples
bashstdinexpect

why expect command works where stdin redirection fails?


I've seen that for some programs, the only way to pass text to their prompt is to use the expect command.

Redirecting input from file or using a "here document" does not work. What does expect do, to pass correctly the text?


Solution

  • For example, for security reasons, when ssh needs to read the user's password it does not read from stdin which can be a tty, file, pipe, or fifo. Instead, ssh directly opens /dev/tty and reads the password from it which is guaranteed to be a tty if it exists (otherwise ssh would fail if /dev/tty is not available).

    See following example (on Linux):

    $ strace ssh -o PreferredAuthentications=password 127.0.0.1
    [...]
    open("/dev/tty", O_RDWR)                = 4
    close(4)                                = 0
    open("/dev/tty", O_RDWR)                = 4
    [...]
    write(4, "[email protected]'s password: ", 27) = 27
    [email protected]'s password:
    read(4,
    

    What Expect does is create a pty and run commands on that pty.