Search code examples
expect

Expect script does not work with multiple password requests


I'm trying to execute a perl script to connect to linux hosts generate a snap and then I need to SCP this snap to my local server. So I have to put password 2 times 1 - to login on the servers and 2 - to SCP the file previously generated. The problem is, my expect script is only working for the first password, would anyone have any idea?

[linuxserver]$ ./mul.sh
spawn perl perlscript.pl
Cleaning up /tmp/logs
Getting logs from server 9.x.x.x using snap
Password:  <------ THIS ITERATION WORKS FINE WITH EXPECT
Password:  <------ THE 2nd ITERATION DOES NOT WORK AND I HAVE TO ADD THE PASSWORD MANUALLY
[linuxserver]$
    export PASSWORD='mypassword'

/usr/bin/expect -c '
    spawn perl perlscript.pl
    expect {
        -nocase "*assword*" {
            send "$env(PASSWORD)\r"
            exp_continue
        }
expect -c "
    expect "*assword*"
    send \$env(PASSWORD)\r
    interact"
    }

interact
'

Solution

  • First, use a quoted heredoc when putting an expect script inside a bash script, it reduces quoting hell significantly.

    It seems you need to enter the passwords and then just wait for the perl program to end:

    1. put multiple patterns in the same expect command
    2. use the special eof pattern to expect the end of the spawned program.
    /usr/bin/expect <<'END_EXPECT'
        set timeout -1
        spawn perl perlscript.pl
        expect {
            -nocase "*assword*" {
                send "$env(PASSWORD)\r"
                exp_continue
            }
            eof
        }
    END_EXPECT