Home > OS >  expect complains that send: spawn id exp6 not open
expect complains that send: spawn id exp6 not open

Time:06-17

I use a script to automatically login with Telnet and run some commands on the remote device. But the below code snippet does not work now and then.

Here is the said script:

        expect << EOS
        log_user 0;
        spawn telnet 192.168.1.51 -l root

        expect "#"
        send "ls; pwd;\r"
                log_user 1;
        expect "#"
                log_user 0;
        send "exit\r"
        expect eof
EOS

Here is the output when the code snippet above works well:

ls; pwd;
testprogram
/root

Here is the output when something wrong occurs:

send: spawn id exp6 not open
    while executing
"send "ls; pwd;\r""

Then I try to run with expect -d to get extra debugging output.

Here is the output when -d is enabled:

expect version 5.45.3
argv[0] = expect  argv[1] = -d  
set argc 0
set argv0 "expect"
set argv ""
executing commands from command file
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {95242}

expect: does "" (spawn_id exp6) match glob pattern "#"? no

expect: does "Trying 192.168.1.51...\r\n" (spawn_id exp6) match glob pattern "#"? no

expect: does "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\n" (spawn_id exp6) match glob pattern "#"? no

expect: does "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\nConnection closed by foreign host.\r\n" (spawn_id exp6) match glob pattern "#"? no
expect: read eof
expect: set expect_out(spawn_id) "exp6"
expect: set expect_out(buffer) "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\nConnection closed by foreign host.\r\n"
send: sending "ls; pwd;\r" to { exp6 send: spawn id exp6 not open
    while executing
"send "ls; pwd;\r""

CodePudding user response:

Notice the "Connection closed by foreign host."

spawn telnet 192.168.1.51 -l root

expect {
    "Connection closed by foreign host." {
        puts "Telnet session closed unexpectedly."
        puts "Please try again."
        exit
    }
    "#"
}

With this form of the expect command, expect is looking for two patterns, and the first one found "wins".

  • if "connection closed" happens, the messages are printed and the program ends
  • if "#" (your prompt) shows up, there's no specific action, so the expect command returns and the rest of your program can carry on

This technique is essential for efficient expect programming where you frequently have to look for multiple patterns.


Looking forward, you might expect to see "Connection closed" at any time: investigate the expect_before command.

  • Related