简体   繁体   中英

Send multiple response to interactive Linux command using expect

I have below task to perform.

  1. Run a linux command 'abc' and it will ask for multiple response
  2. First, there are multiple lines and it is asking to select option from 1-10. Ending with 'run?', always have to select 1
  3. Second, Ending with 'yes/no'. Always 'yes' response
  4. Third, Enter ID. Take one ID as input from a .txt file. There is one ID in each row.
  5. Fourth, y/n. Always select "y" as response.

Step 2-5 should run in loop till all ID's in .txt file get over and step 5 will select 'no' or just exit.

Tried below code in Shell/expect but sometimes it skip the ID's from list or show blank value and sometimes get crash while running and throw error:

*child process exited abnormally
    while executing
"exec cat output.txt | grep -i -B2  "rows selected" > result.txt"
    (file "./cmp-test.sh" line 31)*

Here is the code:

exec echo "" > output.txt  
log_file [pwd]/output.txt
set f [open list.txt r]
# list is the file name contain ID's

set idlist [ split [ read $f ] "\n" ]
close $f

send_user "\n Running script.. \n"

spawn <abc command>
foreach ids $idlist {
expect {
  "run? " { send "1\r" }
}

expect {
  "ACDIG: " { send  "$ids\r" }
}

expect { 
  "n)?"  { send "y\r" } 
}

}

exec cat output.txt | grep -i -B2  "rows selected" > result.txt

You probably don't need expect for this:

while read -r id; do
abc << "answers"
1
yes
$id
y
answers
done < ids.txt

or

while read -r id; do
    printf "%s\n" 1 yes "$id" y | abc
done < ids.txt

You're getting the child process exited abnormally because grep exits with a non-zero status when it can't find the given pattern in its input: that's a "normal" grep exit status, but because it is non-zero, Tcl/expect thinks an error occurred.

Try including spawn within the foreach loop. For example:

#!usr/bin/expect

exec echo "" > output.txt
log_file -a output.txt

set f [open list.txt r]
set idlist [read $f]
close $f

send_user "\n Running script.. \n"

foreach ids $idlist {
    spawn <abc command>

    expect "run? "
    send "1\r"

    expect "ACDIG: "
    send "$ids\r"

    expect "n)?"
    send "y\r"
}

log_file
catch {exec cat output.txt | grep -i -B2  "rows selected" > result.txt}

Hope that extra white space in your second expect isn't causing any issues.

Furthermore, are you closing the log_file process at the end of your script?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM