Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Need Help with Expect Script

    I have an Expect script that uses "spawn su" to perform an operation as root. The script works intermittently. When it fails, it times out waiting for the "# " root prompt. When it succeeds, a message is written to /var/log/messages indicating a session opened for user root, but when it fails, no such message is logged. Any ideas why I get this intermittent behaviour?

    #!/usr/bin/expect --

    if {[llength $argv] < 1} {
    send_user "Missing argument.\n"
    exit 1

    # su to root
    stty -echo
    set timeout -1
    send_user "Enter root password: "
    expect_user {
    -re "(.*)\n" {
    set PASSWORD $expect_out(1,string)
    send_user "\n"
    stty echo
    log_user 0
    set timeout 2
    if [catch "spawn su root" reason] {
    send_user "Failed to spawn su: $reason\n"
    exit 1
    expect "Password:"
    send "$PASSWORD\r"
    expect "\r\n"
    #set timeout 5
    log_user 1
    expect {
    "# " {send_user "\nsu successful.\n"}
    timeout {send_user "\nsu timed out.\n"; exit 1}
    "incorrect" {send_user "\nsu failed.\n"; exit 1}
    set timeout -1

    # Perform root operation here.

    expect "# "
    send "exit\r"
    send_user "\n"
    exit 0

  2. #2
    I think I found a solution by adding a "sleep 0.5" between the "expect "Password:"" and the "send "$PASSWORD\r"". It seems that Expect would sometimes send the password too quickly before su was ready to read it, even though su had sent the "Password:" prompt. This might be related to su turning off input echo or flushing input.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts