为什么 expect 命令在 stdin 重定向失败的地方有效?

why expect command works where stdin redirection fails?

我看到对于某些程序,将文本传递到它们的提示符的唯一方法是使用 expect 命令。

从文件重定向输入或使用 "here document" 不起作用。 期望什么能正确传递文本?

例如,出于安全原因,当 ssh 需要读取用户密码时,它不会从 stdin 中读取,后者可以是 tty文件管道fifo。相反,ssh 直接打开 /dev/tty 并从中读取密码,如果它存在则保证是 tty(否则 ssh 将失败,如果/dev/tty 不可用)。

参见以下示例(在 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, "root@127.0.0.1's password: ", 27) = 27
root@127.0.0.1's password:
read(4,

Expect 所做的是在该 pty 上创建 pty 和 运行 命令。