shell expect

expect for automated interaction

1. Install

expect is based on tcl language, you need to install tcl

(1) Preparation tcl, expect Source Package

(2) Installation Configuration compiled

2.expect command

The core expect that spawn, expect, send, set.

(1) spawn call the command to be executed 

(2) expect to listen interactive output 

(3) send interact input 

(3) set set the variable value 

(4) interact interactive finished, will hand over control of the console. 

(5) expect eof, with spawn, and it shows the capture output terminal terminates, similar if ... endif

other settings

set timeout -1, never expect to set a timeout 

set timeout 300, did not capture the content of listening expect if 300, then exit

3.expect syntax

tcl expect using the syntax

Essentially as follows,

After (1) is a command parameter, each separated by spaces

cmd arg arg arg

 (2) using the variables

$foo

 (3) nested command, a command is output, as an input parameter of another command

cmd1 [cmd2 arg]

 (4) double quotation marks, the phrase labeled as a parameter, the effective symbol $ in double quotes

cmd "hello world $foo"

(5) braces, the phrase is marked as a parameter, but braces can not be extended variable

cmd {hello world}

 (6) backslash, escape

 

3. Example:

First, there is an interactive program main.c

#include <stdio.h>

int main(int argc, char **argv)
{
        int i = 0;
        char buf[BUFSIZ] = {0};
        for (i = 0; i < argc; i++)
                printf("argv[%d]:%s\n", i, argv[i]);

        for (i = 0; i < 4; i++) {
                printf("input\n");
                gets(buf);
                puts(buf);
        }

        return 0;
}

 Use the following sh

#!/usr/local/tcl/bin/expect
spawn ./a.out  # 开启子进程,执行a.out
expect "input"  # 监听 "input"
send "xxxx\n"  
expect "input"
send "xxxx\n"
expect "input"
send "xxxx\n"
expect "input"
send "xxxx\n"
expect eof
exit

 Use command line parameters

seen was [Lindex $ argv 0 ]

The first argument to the command var 0

Used in conjunction with other sh

Due expect a separate shell program, so I can not write in a file, the file can only be invoked.

#!/bin/sh
echo "hello world"
./expect.sh

 

Guess you like

Origin www.cnblogs.com/yangxinrui/p/11307720.html