Doka
Doka

Reputation: 235

Speed of expect script

I have the following expect script to automatize the SSH key generation on Ubuntu. The script runs as expected, and generates the key-pairs, but it takes 50-60 sec to finish.It is much more what I would expect on an empty box.

#!/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."

Any hints or tips what to change?

Edit: Based on the answer of Niall Byrne, I landed at the following expect script, which is quick and handles first time key generation, as well as key regeneration (overwrite).

#!/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
}

Upvotes: 1

Views: 3197

Answers (2)

Niall Byrne
Niall Byrne

Reputation: 2460

I think the main source of your delay is that you are not matching your prompts exactly correct with Expect.

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

You specify regular expression syntax here (-re) many of the characters in your expect patterns are reserved regular expression characters ie. ? ( ) .

The real effect of this line is that it will look for a regular expression matching this line for 10 seconds, then give up and proceed to send the y. You are basically just creating a 10 second delay before sending the 'y'. Other lines in your code have similar characteristics.

Consider revising this line to:

expect {Overwrite (y/n)?}

or

expect -re {Overwrite.*}

(This is in addition to concerns regarding entropy, but this expect problem is responsible for the bulk of the delay you're seeing.)

Upvotes: 4

Yann Ramin
Yann Ramin

Reputation: 33197

You are likely dealing with a lack of entropy. When generating keys, the key generator draws upon the system entropy/random number pool (commonly, /dev/random). If the box has little to no load, the random number pool will block until enough environmentally random information can be collected (timings of network traffic, disk, keyboards, mice, and other I/O devices).

Upvotes: 2

Related Questions