使用expect向交互式Linux命令发送多个响应

时间:2016-09-19 20:22:39

标签: bash expect

我有以下任务要执行。

  1. 运行linux命令'abc',它会要求多次响应
  2. 首先,有多行,要求从1-10中选择选项。以'run?'结尾,总是要选择1
  3. 第二,以'是/否'结束。总是'是'回复
  4. 第三,输入ID。从.txt文件中输入一个ID作为输入。每行中有一个ID。
  5. 第四,y / n。始终选择“y”作为回复。
  6. 步骤2-5应该循环运行,直到.txt文件中的所有ID都结束,第5步将选择“否”或退出。

      

    尝试使用Shell / expect中的代码,但有时会跳过ID   列出或显示空白值,有时会在运行时崩溃   抛出错误:

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

    以下是代码:

    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
    

2 个答案:

答案 0 :(得分:0)

你可能不需要期望:

XMLInputFactory XMLFactory = XMLInputFactory.newInstance();
            XMLStreamReader XMLReader = XMLFactory.createXMLStreamReader(myXMLStream);
            while(XMLReader.hasNext())
            {
                if (XMLReader.getEventType() == XMLStreamReader.START_ELEMENT)
                {        
                   String XMLTag = XMLReader.getLocalName();
                   if(XMLTag.equals("value"))
                   {
                      String idValue = XMLReader.getAttributeValue(null, "id");
                      if (idValue.equals("FILE_CREATE_DATE"))
                      {
                        System.out.println(idValue);
                        XMLReader.nextTag();
                        System.out.println(XMLReader.getElementText());

                      }
                   }
               }    
               XMLReader.next();
            }

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

你得到的是while read -r id; do printf "%s\n" 1 yes "$id" y | abc done < ids.txt ,因为当child process exited abnormally在其输入中找不到给定的模式时,它会以非零状态退出:这是一个“正常”的grep退出状态,但是因为它不为零,Tcl / expect认为发生了错误。

答案 1 :(得分:0)

尝试在spawn循环中加入foreach。例如:

#!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}

希望第二个expect中的额外空格不会导致任何问题。

此外,您是否在脚本末尾关闭了log_file进程?