How to wait for a process to complete using tcl-expect
Asked Answered
H

4

9

I am writing a script using expect in which I have to rlogin to some host & after that I need to send some commands. Now I want to exit to that host and relogin again to some other host and send some commands. But the run of my script is not waiting for first host to complete its jobs and exit instead it sends other commands in between the previous process. How can I achieve this using expect please guide?

Sample code is as follow :

#!/usr/local/bin/expect -f

spawn rlogin host1
expect "%"
send "source xyz.csh\r"
send "exit\r"
expect "%"

spawn rlogin host2
some set of commands
Hydrotropism answered 15/5, 2013 at 10:48 Comment(0)
A
0

Can you elaborate on "still script sending rest of the commands in between the previous process. "

I tried this and it worked.

spawn ssh host1
expect ":"
send pwd1
expect "%"
send "echo hi\r"
expect "%"
send "exit\r"
expect eof
spawn ssh host2    
expect ":"
send pwd2
Albi answered 11/7, 2013 at 9:13 Comment(0)
L
13

you're forgetting to "hit enter". After sending exit, the way to wait for the process to end os expect eof:

send "source xyz.csh\r"
expect "%"
send "exit\r"
expect eof
Lovash answered 15/5, 2013 at 12:0 Comment(3)
it is already there in my code , I forgot to mention it here in my codeHydrotropism
what's already there? the eof or the \r? Please update your question to be more precise.Lovash
expect eof also not working. still script sending rest of the commands in between the previous process.Hydrotropism
C
7

I found this post after I ran into a race condition problem: sometimes the script completed as expected and other times it didn't. Adding a catch statement to the script ensured the desired outcome every time:

[...]
expect eof
catch wait result
Cheep answered 12/1, 2016 at 23:7 Comment(1)
catch "some last line", has successfully removed a race-condition for me. Output from expect is now always complete. Instead of just sometimes.Gut
R
1

Try this construct when command is time consuming:

. . .
send "command\r"

expect {
    timeout {
        puts "Running..."
        exp_continue
    }
    "%PROMPT%" {
        puts "Finished."
    }
}

send "next command\r"
. . .

On timeout you will be continuosly waiting with exp_continue command for %PROMPT%.

Rh answered 29/6, 2014 at 18:2 Comment(0)
A
0

Can you elaborate on "still script sending rest of the commands in between the previous process. "

I tried this and it worked.

spawn ssh host1
expect ":"
send pwd1
expect "%"
send "echo hi\r"
expect "%"
send "exit\r"
expect eof
spawn ssh host2    
expect ":"
send pwd2
Albi answered 11/7, 2013 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.