问题
I am using Ubuntu 14.04 and installed expect. I am trying to write a script to enter password when it prompted.
UPDATED Code:
#!/usr/bin/expect -d
set timeout 20
set pw odroid
spawn sudo apt-get update
expect {\[sudo]\ password for odroid: }
send "$pw\r"
close
Any suggestions? thx
UPDATE Errors:
expect: does "" (spawn_id exp4) match glob pattern "\[sudo]\ password for odroid: "? no
[sudo] password for odroid:
expect: does "[sudo] password for odroid: " (spawn_id exp4) match glob pattern "\[sudo]\ password for odroid: "? yes
expect: set expect_out(0,string) "[sudo] password for odroid: "
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "[sudo] password for odroid: "
send: sending "odroid\r" to { exp4 }
回答1:
You have too many quotes. Choose one of:
expect {\[sudo\] password for odroid: }
expect "\\\[sudo\\\] password for odroid: "
Clearly the first option is better.
Lots of escaping is necessary because 1) square brackets are special in a glob pattern, and 2) square brackets are special Tcl syntax (command substitution) in double quotes but not in curly braces.
回答2:
A more generic way of solving your issue would be matching on assword
expect "*?assword*"
This allows for a more generic script where the username is irrelevant.
I also had the following issue with the snippet below. Basically $pw gets interpreted by the shell and needs to be set outside the expect TCL code.
pw="Password1234"
expect -f - <<-EOF
set timeout 10
spawn sudo mysql_secure_installation
expect "*?assword*"
send -- "$pw\r"
expect eof
EOF
来源:https://stackoverflow.com/questions/38458053/use-expect-to-enter-password-when-need-sudo-in-script