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
}
I think the main source of your delay is that you are not matching your prompts exactly correct with Expect.
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:
or
(This is in addition to concerns regarding entropy, but this expect problem is responsible for the bulk of the delay you’re seeing.)