1

我有以下期望脚本来自动化 Ubuntu 上的 SSH 密钥生成。该脚本按预期运行,并生成密钥对,但需要 50-60 秒才能完成。这比我在空盒子上所期望的要多得多。

#!/usr/bin/expect --
eval spawn /usr/bin/ssh-keygen -t rsa

expect -re {Enter file in which to save the key (/root/.ssh/id_rsa): }
send -- "\r"

expect -re {Overwrite (y/n)? }
send -- "y\r"

expect -re {Enter passphrase (empty for no passphrase): }
send -- "\r"

expect -re {Enter same passphrase again:" }
send -- "\r"

puts "\nEnded expect script."

任何提示或提示要改变什么?

编辑:根据 Niall Byrne 的回答,我找到了以下期望脚本,该脚本快速且可处理首次密钥生成以及密钥重新生成(覆盖)。

#!/usr/bin/expect -f
set timeout -1
spawn /usr/bin/ssh-keygen -t rsa
expect {
  "Enter file in which to save the key" {send -- "\r" ; exp_continue}
  "Overwrite" {send -- "y\r" ; exp_continue}
  "Enter passphrase (empty for no passphrase):" {send -- "\r" ; exp_continue}
  "Enter same passphrase again:" { send -- "\r" ; exp_continue}
  eof
}
4

2 回答 2

4

我认为您延迟的主要原因是您的提示与 Expect 不完全正确。

expect -re {Overwrite (y/n)? }
send -- "y\r"

您在此处指定正则表达式语法 (-re) 您期望模式中的许多字符都是保留的正则表达式字符,即。? ( ) 。

这行的真正效果是它会寻找匹配这行的正则表达式 10 秒,然后放弃并继续发送 y。您基本上只是在发送“y”之前创建了 10 秒的延迟。代码中的其他行具有类似的特征。

考虑将此行修改为:

expect {Overwrite (y/n)?}

或者

expect -re {Overwrite.*}

(这是对熵的关注之外的问题,但这个预期问题是您看到的大部分延迟的原因。)

于 2012-11-02T22:06:18.170 回答
2

您可能正在处理缺乏熵的问题。生成密钥时,密钥生成器利用系统熵/随机数池(通常为 /dev/random)。如果盒子几乎没有负载,随机数池将阻塞,直到可以收集到足够的环境随机信息(网络流量、磁盘、键盘、鼠标和其他 I/O 设备的时序)。

于 2012-11-02T17:13:04.477 回答